<?php
/**
 * ================================================================
 * FAVOURITE MODEL
 * ================================================================
 * File: app/Models/Favourite.php
 * 
 * Handles favorite/wishlist functionality for customers
 * ================================================================
 */

class Favourite {
    private $db;
    
    public function __construct() {
        $this->db = Database::getInstance();
    }
    
    /**
     * Add item to favorites
     */
    public function add($customer_id, $item_id) {
        try {
            $sql = "INSERT INTO favourites (customer_id, item_id, created_at) 
                    VALUES (?, ?, NOW())";
            
            return $this->db->execute($sql, [$customer_id, $item_id]);
        } catch (Exception $e) {
            // If duplicate, it's already favorited
            if (strpos($e->getMessage(), 'Duplicate entry') !== false) {
                return true;
            }
            error_log("Favourite add error: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Remove item from favorites
     */
    public function remove($customer_id, $item_id) {
        $sql = "DELETE FROM favourites WHERE customer_id = ? AND item_id = ?";
        return $this->db->execute($sql, [$customer_id, $item_id]);
    }
    
    /**
     * Check if item is favorited by customer
     */
    public function isFavorited($customer_id, $item_id) {
        $sql = "SELECT id FROM favourites 
                WHERE customer_id = ? AND item_id = ? 
                LIMIT 1";
        
        $result = $this->db->fetch($sql, [$customer_id, $item_id]);
        return !empty($result);
    }
    
    /**
     * Toggle favorite (add if not exists, remove if exists)
     */
    public function toggle($customer_id, $item_id) {
        if ($this->isFavorited($customer_id, $item_id)) {
            $success = $this->remove($customer_id, $item_id);
            return [
                'success' => $success,
                'action' => 'removed',
                'is_favorited' => false,
                'message' => 'Removed from favorites'
            ];
        } else {
            $success = $this->add($customer_id, $item_id);
            return [
                'success' => $success,
                'action' => 'added',
                'is_favorited' => true,
                'message' => 'Added to favorites'
            ];
        }
    }
    
    /**
     * Get all favorites for a customer
     */
    public function getByCustomer($customer_id, $limit = 50, $offset = 0) {
        $limit = (int)$limit;
        $offset = (int)$offset;
        
        $sql = "SELECT 
                f.id as favourite_id, 
                f.created_at,
                i.id as item_id, 
                COALESCE(i.title, 'Untitled') as title, 
                COALESCE(i.slug, '') as slug, 
                i.main_image, 
                COALESCE(i.daily_rate, 0) as daily_rate, 
                COALESCE(i.approval_status, 'pending') as approval_status, 
                COALESCE(i.availability_status, 'unavailable') as availability_status,
                COALESCE(v.business_name, 'Unknown Vendor') as vendor_name,
                COALESCE(c.name, 'Uncategorized') as category_name
                FROM favourites f
                LEFT JOIN items i ON f.item_id = i.id
                LEFT JOIN vendors v ON i.vendor_id = v.id
                LEFT JOIN categories c ON i.category_id = c.id
                WHERE f.customer_id = $customer_id
                ORDER BY f.created_at DESC
                LIMIT $limit OFFSET $offset";
        
        $results = $this->db->fetchAll($sql, []);
        return $results ? $results : [];
    }
    
    /**
     * Count favorites for a customer
     */
    public function countByCustomer($customer_id) {
        $sql = "SELECT COUNT(*) as count FROM favourites WHERE customer_id = ?";
        $result = $this->db->fetch($sql, [$customer_id]);
        return $result['count'] ?? 0;
    }
    
    /**
     * Get favorite IDs for a customer (useful for checking multiple items at once)
     */
    public function getFavoriteIds($customer_id) {
        $sql = "SELECT item_id FROM favourites WHERE customer_id = ?";
        $results = $this->db->fetchAll($sql, [$customer_id]);
        return array_column($results, 'item_id');
    }
    
    /**
     * Remove all favorites for a customer
     */
    public function clearByCustomer($customer_id) {
        $sql = "DELETE FROM favourites WHERE customer_id = ?";
        return $this->db->execute($sql, [$customer_id]);
    }
}