<?php

namespace FleekDash\Controllers\SiteGrowth;

/**
 * Growth Events Repository
 *
 * Handles database operations for site growth events
 * Extracted from SiteGrowthMeterController for better organization
 *
 * @package FleekDash\Controllers\SiteGrowth
 * @since 2.2.0
 */
class GrowthEventsRepository
{
    private $wpdb;
    private $table_events;
    private $table_goals;
    private $table_tracking;

    public function __construct()
    {
        global $wpdb;
        $this->wpdb = $wpdb;
        $this->table_events = $wpdb->prefix . 'fleekdash_site_growth_events';
        $this->table_goals = $wpdb->prefix . 'fleekdash_site_growth_goals';
        $this->table_tracking = $wpdb->prefix . 'fleekdash_site_growth_tracking';
    }

    /**
     * Get all events
     *
     * @param bool $active_only Whether to return only active events
     * @return array Events array
     */
    public function getAllEvents($active_only = false)
    {
        $sql = "SELECT * FROM {$this->table_events} ORDER BY is_active DESC, total_occurrences DESC";
        $events = $this->wpdb->get_results($sql, ARRAY_A);

        if ($active_only) {
            $events = array_values(array_filter($events, function ($event) {
                return (int) ($event['is_active'] ?? 0) === 1;
            }));
        }

        return $events;
    }

    /**
     * Get event by ID
     *
     * @param int $event_id Event ID
     * @return array|null Event data or null if not found
     */
    public function getEventById($event_id)
    {
        $sql = $this->wpdb->prepare(
            "SELECT * FROM {$this->table_events} WHERE id = %d",
            $event_id
        );

        return $this->wpdb->get_row($sql, ARRAY_A);
    }

    /**
     * Create new event
     *
     * @param array $event_data Event data
     * @return int|false Event ID on success, false on failure
     */
    public function createEvent($event_data)
    {
        $result = $this->wpdb->insert(
            $this->table_events,
            $event_data,
            $this->getEventDataFormats()
        );

        return $result ? $this->wpdb->insert_id : false;
    }

    /**
     * Update event
     *
     * @param int $event_id Event ID
     * @param array $event_data Event data to update
     * @return bool Success status
     */
    public function updateEvent($event_id, $event_data)
    {
        $result = $this->wpdb->update(
            $this->table_events,
            $event_data,
            ['id' => $event_id],
            $this->getEventDataFormats(),
            ['%d']
        );

        return $result !== false;
    }

    /**
     * Delete event
     *
     * @param int $event_id Event ID
     * @return bool Success status
     */
    public function deleteEvent($event_id)
    {
        $result = $this->wpdb->delete(
            $this->table_events,
            ['id' => $event_id],
            ['%d']
        );

        return $result !== false;
    }

    /**
     * Get all goals
     *
     * @param bool $active_only Whether to return only active goals
     * @return array Goals array
     */
    public function getAllGoals($active_only = false)
    {
        $where = $active_only ? "WHERE is_active = 1" : "";
        $sql = "SELECT * FROM {$this->table_goals} {$where} ORDER BY target_date ASC";
        
        return $this->wpdb->get_results($sql, ARRAY_A);
    }

    /**
     * Get goal by ID
     *
     * @param int $goal_id Goal ID
     * @return array|null Goal data or null if not found
     */
    public function getGoalById($goal_id)
    {
        $sql = $this->wpdb->prepare(
            "SELECT * FROM {$this->table_goals} WHERE id = %d",
            $goal_id
        );

        return $this->wpdb->get_row($sql, ARRAY_A);
    }

    /**
     * Create new goal
     *
     * @param array $goal_data Goal data
     * @return int|false Goal ID on success, false on failure
     */
    public function createGoal($goal_data)
    {
        $result = $this->wpdb->insert(
            $this->table_goals,
            $goal_data
        );

        return $result ? $this->wpdb->insert_id : false;
    }

    /**
     * Update goal
     *
     * @param int $goal_id Goal ID
     * @param array $goal_data Goal data to update
     * @return bool Success status
     */
    public function updateGoal($goal_id, $goal_data)
    {
        $result = $this->wpdb->update(
            $this->table_goals,
            $goal_data,
            ['id' => $goal_id],
            null,
            ['%d']
        );

        return $result !== false;
    }

    /**
     * Delete goal
     *
     * @param int $goal_id Goal ID
     * @return bool Success status
     */
    public function deleteGoal($goal_id)
    {
        $result = $this->wpdb->delete(
            $this->table_goals,
            ['id' => $goal_id],
            ['%d']
        );

        return $result !== false;
    }

    /**
     * Record event tracking
     *
     * @param int $event_id Event ID
     * @param int $user_id User ID
     * @param int $points Points earned
     * @return int|false Tracking ID on success, false on failure
     */
    public function recordEventTracking($event_id, $user_id, $points)
    {
        $result = $this->wpdb->insert(
            $this->table_tracking,
            [
                'event_id' => $event_id,
                'user_id' => $user_id,
                'points_earned' => $points,
                'tracked_at' => \current_time('mysql')
            ],
            ['%d', '%d', '%d', '%s']
        );

        if ($result) {
            // Update event total occurrences
            $this->wpdb->query($this->wpdb->prepare(
                "UPDATE {$this->table_events} 
                 SET total_occurrences = total_occurrences + 1 
                 WHERE id = %d",
                $event_id
            ));

            return $this->wpdb->insert_id;
        }

        return false;
    }

    /**
     * Get event data formats for wpdb operations
     *
     * @return array Format strings
     */
    private function getEventDataFormats()
    {
        return [
            '%s', // event_name
            '%s', // event_description
            '%s', // event_type
            '%d', // points_value
            '%d', // is_active
            '%s', // tracking_config
        ];
    }
}


