<?php
/**
 * ================================================================
 * TOGGLE FAVOURITE AJAX ENDPOINT
 * ================================================================
 * File: ajax/toggle-favourite.php
 * 
 * Handles adding/removing items from customer favorites
 * ================================================================
 */

header('Content-Type: application/json');

require_once __DIR__ . '/../app/Core/init.php';

// Check if user is logged in as customer
if (!Auth::check() || Auth::userType() !== 'customer') {
    echo json_encode([
        'success' => false,
        'message' => 'Please login as a customer to save favorites'
    ]);
    exit;
}

// Get request data
$item_id = isset($_POST['item_id']) ? (int)$_POST['item_id'] : 0;

// Validate item_id
if ($item_id <= 0) {
    echo json_encode([
        'success' => false,
        'message' => 'Invalid item ID'
    ]);
    exit;
}

try {
    // Get customer
    $customerModel = new Customer();
    $customer = $customerModel->findByUserId(Auth::id());
    
    if (!$customer) {
        echo json_encode([
            'success' => false,
            'message' => 'Customer profile not found'
        ]);
        exit;
    }
    
    // Check if item exists
    $itemModel = new Item();
    $item = $itemModel->findById($item_id);
    
    if (!$item) {
        echo json_encode([
            'success' => false,
            'message' => 'Item not found'
        ]);
        exit;
    }
    
    // Toggle favorite
    $favouriteModel = new Favourite();
    $result = $favouriteModel->toggle($customer['id'], $item_id);
    
    if ($result['success']) {
        echo json_encode([
            'success' => true,
            'action' => $result['action'],
            'is_favorited' => $result['is_favorited'],
            'message' => $result['message']
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'message' => 'Failed to update favorites'
        ]);
    }
    
} catch (Exception $e) {
    error_log("Toggle favourite error: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'An error occurred. Please try again.'
    ]);
}