<?php
namespace TCA\DB;
use TCA\Installer;
if ( ! defined( 'ABSPATH' ) ) { exit; }

class EventsDAO {
    public static function get_all( string $status = '' ): array {
        global $wpdb;
        $where = $status ? $wpdb->prepare( " WHERE status=%s", $status ) : '';
        return $wpdb->get_results( "SELECT * FROM " . Installer::t_events() . "$where ORDER BY created_at DESC", ARRAY_A ) ?: [];
    }
    public static function get_by_id( int $id ): ?array {
        global $wpdb;
        return $wpdb->get_row( $wpdb->prepare( "SELECT * FROM " . Installer::t_events() . " WHERE id=%d", $id ), ARRAY_A ) ?: null;
    }
    public static function insert( array $d ) {
        global $wpdb;
        $r = $wpdb->insert( Installer::t_events(), self::sanitize( $d ), self::formats() );
        return $r ? (int)$wpdb->insert_id : false;
    }
    public static function update( int $id, array $d ): bool {
        global $wpdb;
        return false !== $wpdb->update( Installer::t_events(), self::sanitize( $d ), [ 'id' => $id ], self::formats(), [ '%d' ] );
    }
    public static function set_status( int $id, string $status ): void {
        global $wpdb;
        $wpdb->update( Installer::t_events(), [ 'status' => $status ], [ 'id' => $id ], [ '%s' ], [ '%d' ] );
    }
    public static function delete( int $id ): bool {
        global $wpdb;
        return (bool)$wpdb->delete( Installer::t_events(), [ 'id' => $id ], [ '%d' ] );
    }
    private static function sanitize( array $d ): array {
        return [
            'name'            => sanitize_text_field( $d['name']            ?? '' ),
            'subtitle'        => sanitize_text_field( $d['subtitle']        ?? '' ),
            'date_range'      => sanitize_text_field( $d['date_range']      ?? '' ),
            'venue'           => sanitize_text_field( $d['venue']           ?? '' ),
            'address'         => sanitize_text_field( $d['address']         ?? '' ),
            'cta_text'        => sanitize_text_field( $d['cta_text']        ?? 'Register Now' ),
            'cta_url'         => esc_url_raw( $d['cta_url']                 ?? '' ),
            'color_primary'   => sanitize_hex_color( $d['color_primary']    ?? '#e61a84' ) ?: '#e61a84',
            'color_secondary' => sanitize_hex_color( $d['color_secondary']  ?? '#4e24c0' ) ?: '#4e24c0',
            'color_bg'        => sanitize_hex_color( $d['color_bg']         ?? '#0b0b1c' ) ?: '#0b0b1c',
            'status'          => in_array( $d['status'] ?? '', [ 'draft','live' ] ) ? $d['status'] : 'draft',
        ];
    }
    private static function formats(): array {
        return [ '%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s' ];
    }
}
