<?php
session_start();

$host   = "webdev.iyaserver.com";
$userid = "dhreid_guest";
$userpw = "tPTG;A+J{]Ze";
$db     = "dhreid_marketplace";

$mysql = new mysqli($host, $userid, $userpw, $db);
if($mysql->connect_errno){
    echo json_encode(['success' => false, 'error' => 'db_error']);
    exit();
}
// -----------------------------------------------

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

// 1. Check if user is logged in
if (empty($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'error' => 'not_logged_in']);
    exit;
}

// 2. Get the Item ID from the JSON request
$input = json_decode(file_get_contents('php://input'), true);
$item_id = intval($input['item_id'] ?? 0);
$user_id = $_SESSION['user_id'];

if ($item_id <= 0) {
    echo json_encode(['success' => false, 'error' => 'invalid_item']);
    exit;
}

// 3. Check if already saved
$check = $mysql->prepare("SELECT save_id FROM saved_items WHERE user_id = ? AND item_id = ?");
$check->bind_param("ii", $user_id, $item_id);
$check->execute();
$res = $check->get_result();

if ($res->num_rows > 0) {
    // IT IS SAVED -> REMOVE IT (Toggle Off)
    $del = $mysql->prepare("DELETE FROM saved_items WHERE user_id = ? AND item_id = ?");
    $del->bind_param("ii", $user_id, $item_id);
    $del->execute();
    echo json_encode(['success' => true, 'status' => 'unsaved']);
} else {
    // IT IS NOT SAVED -> ADD IT (Toggle On)
    $ins = $mysql->prepare("INSERT INTO saved_items (user_id, item_id) VALUES (?, ?)");
    $ins->bind_param("ii", $user_id, $item_id);
    $ins->execute();
    echo json_encode(['success' => true, 'status' => 'saved']);
}
?>