<?php
session_start();
header('Content-Type: application/json');
error_reporting(E_ALL);
ini_set('display_errors', 0);

// Database connection
$host = 'localhost';
$db = 'zemaraim_interior';
$user = 'zemaraim';
$password = '8wwxk]-X3Kx]CJ]5';

$conn = new mysqli($host, $user, $password, $db);

if ($conn->connect_error) {
    http_response_code(500);
    die(json_encode(['success' => false, 'message' => 'Database connection failed']));
}

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'User not authenticated']);
    exit;
}

$user_id = $_SESSION['user_id'];
$action = $_GET['action'] ?? '';

try {
    switch ($action) {
        case 'add':
            addToFavorites();
            break;
        case 'remove':
            removeFromFavorites();
            break;
        case 'check':
            checkFavorite();
            break;
        case 'get_all':
            getAllFavorites();
            break;
        default:
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Invalid action']);
    }
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Error: ' . $e->getMessage()
    ]);
}

/**
 * Add product to favorites
 */
function addToFavorites() {
    global $conn, $user_id;
    
    $data = json_decode(file_get_contents('php://input'), true);
    
    if (!isset($data['product_id']) || !isset($data['product_name']) || !isset($data['product_price'])) {
        throw new Exception('Missing required fields: product_id, product_name, product_price');
    }
    
    $product_id = intval($data['product_id']);
    $product_name = trim($data['product_name']);
    $product_price = floatval($data['product_price']);
    $product_image = trim($data['product_image'] ?? '');
    
    // Check if already in favorites
    $check = $conn->prepare("SELECT id FROM favorites WHERE user_id = ? AND product_id = ?");
    if (!$check) throw new Exception("Prepare failed: " . $conn->error);
    
    $check->bind_param("ii", $user_id, $product_id);
    $check->execute();
    $result = $check->get_result();
    
    if ($result->num_rows > 0) {
        echo json_encode([
            'success' => false,
            'message' => 'Product already in favorites'
        ]);
        return;
    }
    
    // Insert into favorites
    $stmt = $conn->prepare("
        INSERT INTO favorites (user_id, product_id, product_name, product_price, product_image, added_at)
        VALUES (?, ?, ?, ?, ?, NOW())
    ");
    
    if (!$stmt) throw new Exception("Prepare failed: " . $conn->error);
    
    $stmt->bind_param("iisds", $user_id, $product_id, $product_name, $product_price, $product_image);
    
    if (!$stmt->execute()) {
        throw new Exception("Execute failed: " . $stmt->error);
    }
    
    echo json_encode([
        'success' => true,
        'message' => 'Added to favorites',
        'product_id' => $product_id
    ]);
}

/**
 * Remove product from favorites
 */
function removeFromFavorites() {
    global $conn, $user_id;
    
    $data = json_decode(file_get_contents('php://input'), true);
    
    if (!isset($data['product_id'])) {
        throw new Exception('Missing product_id');
    }
    
    $product_id = intval($data['product_id']);
    
    // Delete from favorites
    $stmt = $conn->prepare("DELETE FROM favorites WHERE user_id = ? AND product_id = ?");
    if (!$stmt) throw new Exception("Prepare failed: " . $conn->error);
    
    $stmt->bind_param("ii", $user_id, $product_id);
    
    if (!$stmt->execute()) {
        throw new Exception("Execute failed: " . $stmt->error);
    }
    
    echo json_encode([
        'success' => true,
        'message' => 'Removed from favorites',
        'product_id' => $product_id
    ]);
}

/**
 * Check if product is in favorites
 */
function checkFavorite() {
    global $conn, $user_id;
    
    $product_id = intval($_GET['product_id'] ?? 0);
    
    if ($product_id <= 0) {
        throw new Exception('Invalid product_id');
    }
    
    $stmt = $conn->prepare("SELECT id FROM favorites WHERE user_id = ? AND product_id = ?");
    if (!$stmt) throw new Exception("Prepare failed: " . $conn->error);
    
    $stmt->bind_param("ii", $user_id, $product_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $is_favorite = $result->num_rows > 0;
    
    echo json_encode([
        'success' => true,
        'is_favorite' => $is_favorite,
        'product_id' => $product_id
    ]);
}

/**
 * Get all user's favorites
 */
function getAllFavorites() {
    global $conn, $user_id;
    
    $stmt = $conn->prepare("
        SELECT id, product_id, product_name, product_price, product_image, added_at
        FROM favorites
        WHERE user_id = ?
        ORDER BY added_at DESC
    ");
    
    if (!$stmt) throw new Exception("Prepare failed: " . $conn->error);
    
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $favorites = [];
    while ($row = $result->fetch_assoc()) {
        $favorites[] = $row;
    }
    
    echo json_encode([
        'success' => true,
        'count' => count($favorites),
        'favorites' => $favorites
    ]);
}
?>
