<?php
class Deal
{
    public $conn;
    private $table_name = "deals";

    // Object Properties
    public $id;
    public $product_id;
    public $title;
    public $description;
    public $discount_percentage;
    public $original_price;
    public $discounted_price;
    public $is_flash_deal;
    public $flash_deal_hours;
    public $social_requirements;
    public $is_active;

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

    // Generate a new UUID
    private function generateUuid()
    {
        return sprintf(
            '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
            mt_rand(0, 0xffff),
            mt_rand(0, 0xffff),
            mt_rand(0, 0xffff),
            mt_rand(0, 0x0fff) | 0x4000,
            mt_rand(0, 0x3fff) | 0x8000,
            mt_rand(0, 0xffff),
            mt_rand(0, 0xffff),
            mt_rand(0, 0xffff)
        );
    }

    // Get a single deal by its ID
    public function getDealByIdForAdmin($id)
    {
        $query = "SELECT d.*, p.name as product_name, p.brand as product_brand
                  FROM " . $this->table_name . " d
                  LEFT JOIN products p ON d.product_id = p.id
                  WHERE d.id = :id";
        
        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(':id', $id);
        $stmt->execute();
        $deal = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($deal && $deal['social_requirements']) {
            $deal['social_requirements'] = json_decode($deal['social_requirements'], true);
        }
        
        return $deal;
    }

    // Create a new deal
    public function create()
    {
        $this->id = $this->generateUuid();
        
        $query = "INSERT INTO " . $this->table_name . "
                  SET id = :id, product_id = :product_id, title = :title, description = :description,
                      discount_percentage = :discount_percentage, original_price = :original_price,
                      discounted_price = :discounted_price, is_flash_deal = :is_flash_deal,
                      flash_deal_hours = :flash_deal_hours, social_requirements = :social_requirements";

        $stmt = $this->conn->prepare($query);

        // Sanitize data
        $this->product_id = htmlspecialchars(strip_tags($this->product_id));
        $this->title = htmlspecialchars(strip_tags($this->title));
        $this->description = htmlspecialchars(strip_tags($this->description));

        // Bind data
        $stmt->bindParam(':id', $this->id);
        $stmt->bindParam(':product_id', $this->product_id);
        $stmt->bindParam(':title', $this->title);
        $stmt->bindParam(':description', $this->description);
        $stmt->bindParam(':discount_percentage', $this->discount_percentage);
        $stmt->bindParam(':original_price', $this->original_price);
        $stmt->bindParam(':discounted_price', $this->discounted_price);
        $stmt->bindParam(':is_flash_deal', $this->is_flash_deal, PDO::PARAM_BOOL);
        $stmt->bindParam(':flash_deal_hours', $this->flash_deal_hours);
        $stmt->bindParam(':social_requirements', $this->social_requirements);

        if ($stmt->execute()) {
            return $this->id;
        }
        return false;
    }

    // Update an existing deal
    public function update()
    {
        $query = "UPDATE " . $this->table_name . "
                  SET title = :title, description = :description, discount_percentage = :discount_percentage,
                      original_price = :original_price, discounted_price = :discounted_price,
                      is_flash_deal = :is_flash_deal, flash_deal_hours = :flash_deal_hours,
                      is_active = :is_active" .
                 (isset($this->social_requirements) ? ", social_requirements = :social_requirements" : "") .
                 " WHERE id = :id";
        
        $stmt = $this->conn->prepare($query);

        // Sanitize and bind data
        $stmt->bindParam(':id', $this->id);
        $stmt->bindParam(':title', $this->title);
        $stmt->bindParam(':description', $this->description);
        $stmt->bindParam(':discount_percentage', $this->discount_percentage);
        $stmt->bindParam(':original_price', $this->original_price);
        $stmt->bindParam(':discounted_price', $this->discounted_price);
        $stmt->bindParam(':is_flash_deal', $this->is_flash_deal, PDO::PARAM_BOOL);
        $stmt->bindParam(':flash_deal_hours', $this->flash_deal_hours);
        $stmt->bindParam(':is_active', $this->is_active, PDO::PARAM_BOOL);
        if (isset($this->social_requirements)) {
            $stmt->bindParam(':social_requirements', $this->social_requirements);
        }

        return $stmt->execute();
    }

    // Delete a deal
    public function delete()
    {
        $query = "DELETE FROM " . $this->table_name . " WHERE id = :id";
        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(':id', $this->id);
        return $stmt->execute();
    }

    // Get active deals for users
    public function getActiveDeals($limit = 20)
    {
        $query = "SELECT 
                    d.*, 
                    COALESCE(p.name, 'Unknown Product') as product_name, 
                    COALESCE(p.brand, 'Unknown Brand') as product_brand,
                    COALESCE(p.base_price, d.original_price) as base_price,
                    (SELECT pi.url FROM product_images pi WHERE pi.product_id = d.product_id ORDER BY pi.position ASC LIMIT 1) as product_image,
                    CASE 
                        WHEN d.is_flash_deal = 1 AND d.created_at + INTERVAL d.flash_deal_hours HOUR > NOW() THEN d.created_at + INTERVAL d.flash_deal_hours HOUR
                        ELSE NULL 
                    END as expires_at
                  FROM " . $this->table_name . " d
                  LEFT JOIN products p ON d.product_id = p.id
                  WHERE d.is_active = 1 
                  AND d.title IS NOT NULL AND d.title != '' AND d.title != 'undefined'
                  AND (d.is_flash_deal = 0 OR (d.is_flash_deal = 1 AND d.created_at + INTERVAL d.flash_deal_hours HOUR > NOW()))
                  ORDER BY d.is_flash_deal DESC, d.created_at DESC
                  LIMIT :limit";
        
        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(':limit', $limit, PDO::PARAM_INT);
        $stmt->execute();
        $deals = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Parse social requirements for each deal and ensure data integrity
        foreach ($deals as &$deal) {
            if ($deal['social_requirements']) {
                $deal['social_requirements'] = json_decode($deal['social_requirements'], true);
            }
            
            // Ensure title is not undefined
            if (empty($deal['title']) || $deal['title'] === 'undefined') {
                $deal['title'] = 'Deal for ' . $deal['product_name'];
            }
            
            // Ensure product name is not undefined
            if (empty($deal['product_name']) || $deal['product_name'] === 'undefined') {
                $deal['product_name'] = 'Unknown Product';
            }
        }
        
        return $deals;
    }

    // Get a single deal by ID for users
    public function getDealById($id)
    {
        $query = "SELECT 
                    d.*, 
                    p.name as product_name, 
                    p.brand as product_brand,
                    p.base_price,
                    p.description as product_description,
                    p.specifications as product_specifications,
                    (SELECT GROUP_CONCAT(pi.url) FROM product_images pi WHERE pi.product_id = d.product_id ORDER BY pi.position ASC) as product_images,
                    CASE 
                        WHEN d.is_flash_deal = 1 AND d.created_at + INTERVAL d.flash_deal_hours HOUR > NOW() THEN d.created_at + INTERVAL d.flash_deal_hours HOUR
                        ELSE NULL 
                    END as expires_at
                  FROM " . $this->table_name . " d
                  LEFT JOIN products p ON d.product_id = p.id
                  WHERE d.id = :id AND d.is_active = 1";
        
        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(':id', $id);
        $stmt->execute();
        $deal = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($deal) {
            // Parse social requirements
            if ($deal['social_requirements']) {
                $deal['social_requirements'] = json_decode($deal['social_requirements'], true);
            }
            
            // Parse product images
            if ($deal['product_images']) {
                $deal['product_images'] = explode(',', $deal['product_images']);
            }
        }
        
        return $deal;
    }

    // Get user's progress for a specific deal
    public function getUserDealProgress($userId, $dealId)
    {
        // Check if user_deal_progress table exists, if not create it
        $this->createUserProgressTable();
        
        $query = "SELECT * FROM user_deal_progress WHERE user_id = :user_id AND deal_id = :deal_id";
        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(':user_id', $userId);
        $stmt->bindParam(':deal_id', $dealId);
        $stmt->execute();
        $progress = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$progress) {
            // Create initial progress record
            $insertQuery = "INSERT INTO user_deal_progress (user_id, deal_id, instagram_verified, youtube_verified, deal_unlocked) 
                           VALUES (:user_id, :deal_id, 0, 0, 0)";
            $insertStmt = $this->conn->prepare($insertQuery);
            $insertStmt->bindParam(':user_id', $userId);
            $insertStmt->bindParam(':deal_id', $dealId);
            $insertStmt->execute();
            
            $progress = [
                'user_id' => $userId,
                'deal_id' => $dealId,
                'instagram_verified' => false,
                'youtube_verified' => false,
                'deal_unlocked' => false
            ];
        } else {
            $progress['instagram_verified'] = (bool)$progress['instagram_verified'];
            $progress['youtube_verified'] = (bool)$progress['youtube_verified'];
            $progress['deal_unlocked'] = (bool)$progress['deal_unlocked'];
        }
        
        return $progress;
    }

    // Update user's progress for a deal
    public function updateUserProgress($userId, $dealId, $platform, $verified)
    {
        // Check if user_deal_progress table exists, if not create it
        $this->createUserProgressTable();
        
        // Get current progress
        $progress = $this->getUserDealProgress($userId, $dealId);
        
        // Update the specific platform
        $field = $platform . '_verified';
        $query = "UPDATE user_deal_progress SET {$field} = :verified WHERE user_id = :user_id AND deal_id = :deal_id";
        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(':verified', $verified, PDO::PARAM_BOOL);
        $stmt->bindParam(':user_id', $userId);
        $stmt->bindParam(':deal_id', $dealId);
        $result = $stmt->execute();
        
        if ($result) {
            // Check if deal should be unlocked (both platforms verified)
            $updatedProgress = $this->getUserDealProgress($userId, $dealId);
            if ($updatedProgress['instagram_verified'] && $updatedProgress['youtube_verified']) {
                $unlockQuery = "UPDATE user_deal_progress SET deal_unlocked = 1 WHERE user_id = :user_id AND deal_id = :deal_id";
                $unlockStmt = $this->conn->prepare($unlockQuery);
                $unlockStmt->bindParam(':user_id', $userId);
                $unlockStmt->bindParam(':deal_id', $dealId);
                $unlockStmt->execute();
            }
        }
        
        return $result;
    }

    // Create user progress table if it doesn't exist
    private function createUserProgressTable()
    {
        $query = "CREATE TABLE IF NOT EXISTS user_deal_progress (
            id INT AUTO_INCREMENT PRIMARY KEY,
            user_id VARCHAR(36) NOT NULL,
            deal_id VARCHAR(36) NOT NULL,
            instagram_verified BOOLEAN DEFAULT FALSE,
            youtube_verified BOOLEAN DEFAULT FALSE,
            deal_unlocked BOOLEAN DEFAULT FALSE,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            UNIQUE KEY unique_user_deal (user_id, deal_id),
            FOREIGN KEY (deal_id) REFERENCES deals(id) ON DELETE CASCADE
        )";
        
        $this->conn->exec($query);
    }

    // Get all deals for admin (including inactive)
    public function getAllDealsForAdmin()
    {
        $query = "SELECT 
                    d.*, 
                    COALESCE(p.name, 'Unknown Product') as product_name, 
                    COALESCE(p.brand, 'Unknown Brand') as product_brand,
                    COALESCE(p.base_price, d.original_price) as base_price,
                    (SELECT pi.url FROM product_images pi WHERE pi.product_id = d.product_id ORDER BY pi.position ASC LIMIT 1) as product_image,
                    CASE 
                        WHEN d.is_flash_deal = 1 AND d.created_at + INTERVAL d.flash_deal_hours HOUR > NOW() THEN d.created_at + INTERVAL d.flash_deal_hours HOUR
                        ELSE NULL 
                    END as expires_at
                  FROM " . $this->table_name . " d
                  LEFT JOIN products p ON d.product_id = p.id
                  WHERE d.title IS NOT NULL AND d.title != '' AND d.title != 'undefined'
                  ORDER BY d.created_at DESC";
        
        $stmt = $this->conn->prepare($query);
        $stmt->execute();
        $deals = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Parse social requirements for each deal and ensure data integrity
        foreach ($deals as &$deal) {
            if ($deal['social_requirements']) {
                $deal['social_requirements'] = json_decode($deal['social_requirements'], true);
            }
            
            // Ensure title is not undefined
            if (empty($deal['title']) || $deal['title'] === 'undefined') {
                $deal['title'] = 'Deal for ' . $deal['product_name'];
            }
            
            // Ensure product name is not undefined
            if (empty($deal['product_name']) || $deal['product_name'] === 'undefined') {
                $deal['product_name'] = 'Unknown Product';
            }
        }
        
        return $deals;
    }
}
?>