<?php
/**
 * TitanCart Calendar Manager
 *
 * CRUD for calendar events.
 *
 * @package TitanCart\Modules\Calendar
 */

namespace TitanCart\Modules\Calendar;

defined( 'ABSPATH' ) || exit;

class CalendarManager {

    private $db;

    public function __construct() {
        $this->db = titancart_db();
    }

    private function t( string $name ): string {
        return $this->db->table( $name );
    }

    /**
     * Get events for a date range (typically one month view).
     */
    public function get_events( string $from, string $to ): array {
        global $wpdb;
        $rows = $wpdb->get_results( $wpdb->prepare(
            "SELECT e.*, u.display_name AS created_by_name
             FROM {$this->t('calendar_events')} e
             LEFT JOIN {$wpdb->users} u ON u.ID = e.created_by
             WHERE e.event_date >= %s AND e.event_date <= %s
             ORDER BY e.event_date ASC, e.start_time ASC",
            $from, $to
        ), ARRAY_A );
        return $rows ?: [];
    }

    /**
     * Get events for a single date.
     */
    public function get_events_for_date( string $date ): array {
        global $wpdb;
        $rows = $wpdb->get_results( $wpdb->prepare(
            "SELECT e.*, u.display_name AS created_by_name
             FROM {$this->t('calendar_events')} e
             LEFT JOIN {$wpdb->users} u ON u.ID = e.created_by
             WHERE e.event_date = %s
             ORDER BY e.all_day DESC, e.start_time ASC",
            $date
        ), ARRAY_A );
        return $rows ?: [];
    }

    /**
     * Get a single event.
     */
    public function get( int $id ): ?array {
        global $wpdb;
        return $wpdb->get_row( $wpdb->prepare(
            "SELECT e.*, u.display_name AS created_by_name
             FROM {$this->t('calendar_events')} e
             LEFT JOIN {$wpdb->users} u ON u.ID = e.created_by
             WHERE e.id = %d",
            $id
        ), ARRAY_A );
    }

    /**
     * Create an event.
     */
    public function create( array $data ): int {
        global $wpdb;
        $all_day = ! empty( $data['all_day'] ) ? 1 : 0;
        $wpdb->insert( $this->t('calendar_events'), [
            'title'       => sanitize_text_field( $data['title'] ?? '' ),
            'description' => sanitize_textarea_field( $data['description'] ?? '' ),
            'event_date'  => sanitize_text_field( $data['event_date'] ?? '' ),
            'start_time'  => ! $all_day && ! empty( $data['start_time'] ) ? sanitize_text_field( $data['start_time'] ) : null,
            'end_time'    => ! $all_day && ! empty( $data['end_time'] ) ? sanitize_text_field( $data['end_time'] ) : null,
            'all_day'     => $all_day,
            'color'       => sanitize_hex_color( $data['color'] ?? '#2563EB' ) ?: '#2563EB',
            'created_by'  => get_current_user_id(),
        ] );
        return (int) $wpdb->insert_id;
    }

    /**
     * Update an event.
     */
    public function update( int $id, array $data ): bool {
        global $wpdb;
        $update = [];

        if ( isset( $data['title'] ) )       $update['title']       = sanitize_text_field( $data['title'] );
        if ( isset( $data['description'] ) )  $update['description'] = sanitize_textarea_field( $data['description'] );
        if ( isset( $data['event_date'] ) )   $update['event_date']  = sanitize_text_field( $data['event_date'] );
        if ( isset( $data['color'] ) )        $update['color']       = sanitize_hex_color( $data['color'] ) ?: '#2563EB';

        if ( isset( $data['all_day'] ) ) {
            $update['all_day'] = ! empty( $data['all_day'] ) ? 1 : 0;
            if ( $update['all_day'] ) {
                $update['start_time'] = null;
                $update['end_time']   = null;
            }
        }
        if ( isset( $data['start_time'] ) ) $update['start_time'] = $data['start_time'] ?: null;
        if ( isset( $data['end_time'] ) )   $update['end_time']   = $data['end_time'] ?: null;

        if ( $update ) {
            $wpdb->update( $this->t('calendar_events'), $update, [ 'id' => $id ] );
        }
        return true;
    }

    /**
     * Delete an event.
     */
    public function delete( int $id ): bool {
        global $wpdb;
        $wpdb->delete( $this->t('calendar_events'), [ 'id' => $id ] );
        return true;
    }
}
