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

class SlotsDAO {
    private static function normalize( array $row ): array {
        $row['event_day']  = $row['slot_date'] ?? ( $row['event_day'] ?? '' );
        $row['start_time'] = $row['time_start'] ?? ( $row['start_time'] ?? '' );
        $row['end_time']   = $row['time_end'] ?? ( $row['end_time'] ?? '' );
        $row['is_booked']  = ( isset( $row['status'] ) && $row['status'] !== 'available' ) ? 1 : 0;
        return $row;
    }
    public static function get_available( int $partner_id ): array {
        global $wpdb;
        $rows = $wpdb->get_results( $wpdb->prepare(
            "SELECT * FROM " . Installer::t_slots() . " WHERE partner_id=%d AND status='available' ORDER BY slot_date ASC, time_start ASC",
            $partner_id
        ), ARRAY_A ) ?: [];
        return array_map( [ self::class, 'normalize' ], $rows );
    }
    public static function get_by_partner( int $partner_id ): array {
        global $wpdb;
        $rows = $wpdb->get_results( $wpdb->prepare(
            "SELECT * FROM " . Installer::t_slots() . " WHERE partner_id=%d ORDER BY slot_date ASC, time_start ASC",
            $partner_id
        ), ARRAY_A ) ?: [];
        return array_map( [ self::class, 'normalize' ], $rows );
    }
    public static function get_by_id( int $id ): ?array {
        global $wpdb;
        $row = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM " . Installer::t_slots() . " WHERE id=%d", $id ), ARRAY_A );
        return $row ? self::normalize( $row ) : null;
    }
    public static function reserve( int $slot_id ): bool {
        global $wpdb;
        return (bool) $wpdb->query( $wpdb->prepare( "UPDATE " . Installer::t_slots() . " SET status='pending' WHERE id=%d AND status='available'", $slot_id ) );
    }
    public static function release( int $slot_id ): bool {
        global $wpdb;
        return $wpdb->update( Installer::t_slots(), [ 'status' => 'available', 'speaker_id' => 0 ], [ 'id' => $slot_id ] ) !== false;
    }
}
