<?php

require_once __DIR__ . '/BaseModel.php';

class BannerModel extends BaseModel
{

    protected $table = 'banners';

    /**
     * Get active banners
     */
    public function getActiveBanners($idMitra = 1, $limit = null)
    {
        $sql = "SELECT 
                    id, id_mitra, title, description, image_url, 
                    link_url, is_active, created_at, valid_until, display_order
                FROM {$this->table} 
                WHERE is_active = 1 
                AND id_mitra = ? 
                AND (valid_until IS NULL OR valid_until > NOW()) 
                ORDER BY display_order ASC, created_at DESC";

        if ($limit) {
            $sql .= " LIMIT ?";
        }

        $stmt = $this->db->prepare($sql);
        if (!$stmt) {
            throw new Exception("Database prepare error: " . $this->db->error);
        }

        if ($limit) {
            $stmt->bind_param("ii", $idMitra, $limit);
        } else {
            $stmt->bind_param("i", $idMitra);
        }

        $stmt->execute();
        $result = $stmt->get_result();

        $banners = [];
        while ($row = $result->fetch_assoc()) {
            $banners[] = $this->formatBannerData($row);
        }

        $stmt->close();
        return $banners;
    }

    /**
     * Get banner by ID
     */
    public function getBannerById($id, $idMitra = 1)
    {
        $stmt = $this->db->prepare("
            SELECT 
                id, id_mitra, title, description, image_url, 
                link_url, is_active, created_at, valid_until, display_order
            FROM {$this->table} 
            WHERE id = ? 
            AND is_active = 1 
            AND id_mitra = ? 
            AND (valid_until IS NULL OR valid_until > NOW())
            LIMIT 1
        ");

        if (!$stmt) {
            throw new Exception("Database prepare error: " . $this->db->error);
        }

        $stmt->bind_param("ii", $id, $idMitra);
        $stmt->execute();
        $result = $stmt->get_result();
        $banner = $result->fetch_assoc();
        $stmt->close();

        return $banner ? $this->formatBannerData($banner) : null;
    }

    /**
     * Save banner click
     */
    public function saveBannerClick($userId, $idMitra)
    {
        $stmt = $this->db->prepare("INSERT INTO banner_clicks (user_id, id_mitra, clicked_at) VALUES (?, ?, NOW())");
        if (!$stmt) {
            throw new Exception("Database prepare error: " . $this->db->error);
        }

        $stmt->bind_param("ii", $userId, $idMitra);
        $result = $stmt->execute();
        $insertId = $this->db->insert_id;
        $stmt->close();

        return $result ? $insertId : false;
    }

    /**
     * Get banner click statistics
     */
    public function getBannerClickStats($idMitra, $dateFrom = null, $dateTo = null)
    {
        $sql = "SELECT 
                    COUNT(*) as total_clicks,
                    COUNT(DISTINCT user_id) as unique_users,
                    DATE(clicked_at) as click_date
                FROM banner_clicks 
                WHERE id_mitra = ?";

        $params = [$idMitra];
        $types = "i";

        if ($dateFrom) {
            $sql .= " AND DATE(clicked_at) >= ?";
            $params[] = $dateFrom;
            $types .= "s";
        }

        if ($dateTo) {
            $sql .= " AND DATE(clicked_at) <= ?";
            $params[] = $dateTo;
            $types .= "s";
        }

        $sql .= " GROUP BY DATE(clicked_at) ORDER BY click_date DESC";

        $stmt = $this->db->prepare($sql);
        if (!$stmt) {
            throw new Exception("Database prepare error: " . $this->db->error);
        }

        $stmt->bind_param($types, ...$params);
        $stmt->execute();
        $result = $stmt->get_result();

        $stats = [];
        while ($row = $result->fetch_assoc()) {
            $stats[] = $row;
        }

        $stmt->close();
        return $stats;
    }

    /**
     * Check if user exists (for click validation)
     */
    public function userExists($userId)
    {
        $stmt = $this->db->prepare("SELECT id FROM user WHERE id = ? LIMIT 1");
        if (!$stmt) {
            throw new Exception("Database prepare error: " . $this->db->error);
        }

        $stmt->bind_param("i", $userId);
        $stmt->execute();
        $result = $stmt->get_result();
        $exists = $result->num_rows > 0;
        $stmt->close();

        return $exists;
    }

    /**
     * Format banner data for API response
     */
    private function formatBannerData($banner)
    {
        return [
            'id' => (int) $banner['id'],
            'id_mitra' => (int) $banner['id_mitra'],
            'title' => $banner['title'],
            'description' => $banner['description'],
            'image_url' => $banner['image_url'],
            'link_url' => $banner['link_url'],
            'is_active' => (bool) $banner['is_active'],
            'display_order' => (int) $banner['display_order'],
            'created_at' => $banner['created_at'],
            'valid_until' => $banner['valid_until']
        ];
    }

    /**
     * Create new banner
     */
    public function createBanner($bannerData)
    {
        $bannerData['created_at'] = date('Y-m-d H:i:s');
        $bannerData['is_active'] = $bannerData['is_active'] ?? 1;

        return $this->create($bannerData);
    }

    /**
     * Update banner
     */
    public function updateBanner($id, $bannerData)
    {
        $bannerData['updated_at'] = date('Y-m-d H:i:s');

        return $this->update($id, $bannerData);
    }

    /**
     * Deactivate banner
     */
    public function deactivateBanner($id)
    {
        return $this->updateBanner($id, ['is_active' => 0]);
    }

    /**
     * Get banners by status
     */
    public function getBannersByStatus($isActive, $idMitra = 1)
    {
        $conditions = [
            'is_active' => $isActive ? 1 : 0,
            'id_mitra' => $idMitra
        ];

        $banners = $this->findAll($conditions, 'display_order ASC, created_at DESC');

        return array_map([$this, 'formatBannerData'], $banners);
    }
}
