<?php
require_once __DIR__ . '/../../../../helpers/response.php';
require_once __DIR__ . '/../../../../helpers/validation.php';
require_once __DIR__ . '/../../../Middleware/AuthMiddleware.php';
require_once __DIR__ . '/../../../Models/Database.php';

class FavoritesController {
    
    public function getMaids() {
        $payload = AuthMiddleware::authenticate('customer');
        $customerId = $payload['id'];
        
        $db = Database::getInstance();

        $page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
        $limit = isset($_GET['limit']) ? max(1, intval($_GET['limit'])) : 10;
        $offset = ($page - 1) * $limit;

        $totalStmt = $db->prepare("
            SELECT COUNT(*)
            FROM favorite_maids fm
            JOIN maids m ON fm.maid_id = m.id
            JOIN vendors v ON m.vendor_id = v.id
            WHERE fm.customer_id = ? AND v.status = 'approved'
        ");
        $totalStmt->execute([$customerId]);
        $total = (int) $totalStmt->fetchColumn();

        $stmt = $db->prepare("
            SELECT m.id, m.full_name, m.monthly_salary, m.years_experience, m.profile_image,
                   n.name_en as nationality_name, fm.created_at as favorited_at
            FROM favorite_maids fm
            JOIN maids m ON fm.maid_id = m.id
            JOIN vendors v ON m.vendor_id = v.id
            LEFT JOIN nationalities n ON m.nationality_id = n.id
            WHERE fm.customer_id = ? AND v.status = 'approved'
            ORDER BY fm.created_at DESC
            LIMIT " . intval($limit) . " OFFSET " . intval($offset) . "
        ");
        $stmt->execute([$customerId]);
        $maids = $stmt->fetchAll();
        
        $pagination = [
            'total' => $total,
            'page' => $page,
            'limit' => $limit,
            'total_pages' => ceil($total / $limit)
        ];

        jsonResponse(true, 'Favorite maids loaded', ['maids' => $maids], $pagination);
    }
    
    public function toggleMaid() {
        $payload = AuthMiddleware::authenticate('customer');
        $customerId = $payload['id'];
        
        $data = json_decode(file_get_contents('php://input'), true);
        if (!$data) $data = $_POST;
        
        $errors = validateRequired($data, ['maid_id']);
        if (!empty($errors)) {
            sendError('Validation failed', $errors, 422);
        }
        
        $db = Database::getInstance();
        
        // Check if already favorited
        $stmt = $db->prepare("SELECT id FROM favorite_maids WHERE customer_id = ? AND maid_id = ?");
        $stmt->execute([$customerId, $data['maid_id']]);
        $favorite = $stmt->fetch();
        
        if ($favorite) {
            $stmt = $db->prepare("DELETE FROM favorite_maids WHERE id = ?");
            $stmt->execute([$favorite['id']]);
            sendResponse(['favorited' => false], 'Maid removed from favorites');
        } else {
            // Verify maid exists and vendor is approved
            $stmt = $db->prepare("
                SELECT m.id FROM maids m 
                JOIN vendors v ON m.vendor_id = v.id 
                WHERE m.id = ? AND v.status = 'approved'
            ");
            $stmt->execute([$data['maid_id']]);
            if (!$stmt->fetch()) {
                sendError('Maid not found', [], 404);
            }
            
            $stmt = $db->prepare("INSERT INTO favorite_maids (customer_id, maid_id) VALUES (?, ?)");
            $stmt->execute([$customerId, $data['maid_id']]);
            sendResponse(['favorited' => true], 'Maid added to favorites');
        }
    }
    
    public function getVendors() {
        $payload = AuthMiddleware::authenticate('customer');
        $customerId = $payload['id'];
        
        $db = Database::getInstance();

        $page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
        $limit = isset($_GET['limit']) ? max(1, intval($_GET['limit'])) : 10;
        $offset = ($page - 1) * $limit;

        $totalStmt = $db->prepare("
            SELECT COUNT(*)
            FROM favorite_vendors fv
            JOIN vendors v ON fv.vendor_id = v.id
            WHERE fv.customer_id = ? AND v.status = 'approved'
        ");
        $totalStmt->execute([$customerId]);
        $total = (int) $totalStmt->fetchColumn();

        $stmt = $db->prepare("
            SELECT v.id, v.agency_name, v.logo, v.description, v.cover_image, v.is_verified,
                   fv.created_at as favorited_at
            FROM favorite_vendors fv
            JOIN vendors v ON fv.vendor_id = v.id
            WHERE fv.customer_id = ? AND v.status = 'approved'
            ORDER BY fv.created_at DESC
            LIMIT " . intval($limit) . " OFFSET " . intval($offset) . "
        ");
        $stmt->execute([$customerId]);
        $vendors = $stmt->fetchAll();
        
        $pagination = [
            'total' => $total,
            'page' => $page,
            'limit' => $limit,
            'total_pages' => ceil($total / $limit)
        ];

        jsonResponse(true, 'Favorite vendors loaded', ['vendors' => $vendors], $pagination);
    }
    
    public function toggleVendor() {
        $payload = AuthMiddleware::authenticate('customer');
        $customerId = $payload['id'];
        
        $data = json_decode(file_get_contents('php://input'), true);
        if (!$data) $data = $_POST;
        
        $errors = validateRequired($data, ['vendor_id']);
        if (!empty($errors)) {
            sendError('Validation failed', $errors, 422);
        }
        
        $db = Database::getInstance();
        
        // Check if already favorited
        $stmt = $db->prepare("SELECT id FROM favorite_vendors WHERE customer_id = ? AND vendor_id = ?");
        $stmt->execute([$customerId, $data['vendor_id']]);
        $favorite = $stmt->fetch();
        
        if ($favorite) {
            $stmt = $db->prepare("DELETE FROM favorite_vendors WHERE id = ?");
            $stmt->execute([$favorite['id']]);
            sendResponse(['favorited' => false], 'Vendor removed from favorites');
        } else {
            // Verify vendor exists and is approved
            $stmt = $db->prepare("SELECT id FROM vendors WHERE id = ? AND status = 'approved'");
            $stmt->execute([$data['vendor_id']]);
            if (!$stmt->fetch()) {
                sendError('Vendor not found', [], 404);
            }
            
            $stmt = $db->prepare("INSERT INTO favorite_vendors (customer_id, vendor_id) VALUES (?, ?)");
            $stmt->execute([$customerId, $data['vendor_id']]);
            sendResponse(['favorited' => true], 'Vendor added to favorites');
        }
    }
}
