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

$data = json_decode(file_get_contents("php://input"), true);

$servername = "localhost"; // Replace with your database credentials
$username = "u111585590_cookies";
$password = "Cookies@076";
$dbname = "u111585590_db_cookies";

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die(json_encode(['error' => 'Connection failed: ' . $conn->connect_error]));
}

// Check if table exists, create if not (with UNIQUE constraint)
$tableCheckSql = "SHOW TABLES LIKE 'cookies'";
$tableCheckResult = $conn->query($tableCheckSql);

if ($tableCheckResult->num_rows == 0) {
    $tableCreateSql = "CREATE TABLE cookies (
        id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        web VARCHAR(30) UNIQUE NOT NULL,
        url VARCHAR(255) NOT NULL,
        cookies TEXT NOT NULL
    )";

    if (!$conn->query($tableCreateSql)) {
        die(json_encode(['error' => 'Error creating table: ' . $conn->error]));
    }
}

// Prepare the statement (using named placeholders for clarity)
$select_sql = "SELECT id FROM cookies WHERE web = ?";
$stmt_select = $conn->prepare($select_sql);
$stmt_select->bind_param("s", $data['web']);
$stmt_select->execute();
$stmt_select->store_result(); // Store the result to check num_rows later

if ($stmt_select->num_rows > 0) {
    $update_sql = "UPDATE cookies SET url = ?, cookies = ? WHERE web = ?";
    $stmt_update = $conn->prepare($update_sql);
    $stmt_update->bind_param("sss", $data['url'], $data['cookies'], $data['web']);
    $stmt_update->execute();
} else {
    $insert_sql = "INSERT INTO cookies (web, url, cookies) VALUES (?, ?, ?)";
    $stmt_insert = $conn->prepare($insert_sql);
    $stmt_insert->bind_param("sss", $data['web'], $data['url'], $data['cookies']);
    $stmt_insert->execute(); 
}
echo json_encode(['success' => 'Cookies saved successfully']);
$conn->close();
?>
