<?php
header('Content-Type: application/json');
header("Access-Control-Allow-Origin: *"); // Allow from any origin
header("Access-Control-Allow-Methods: GET, POST, OPTIONS"); 
header("Access-Control-Allow-Headers: Content-Type"); 
$servername = "localhost";
$username = "skilled4_cookiespkryk";
$password = "Jv9MwST]hB&K";
$dbname = "skilled4_cookies";
function connectToDatabase() {
    global $servername, $username, $password, $dbname;
    $conn = new mysqli($servername, $username, $password, $dbname);
    if ($conn->connect_error) {
        die(json_encode(['error' => 'Connection failed: ' . $conn->connect_error]));
    }
        createUsersTable($conn); 
    return $conn;
}
function createUsersTable($conn) {
    $tableCreateSql = "CREATE TABLE IF NOT EXISTS users (
        id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(50),
        username VARCHAR(50),
        password VARCHAR(255)
    )";

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

function createCookiesTable($conn) {
    $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]));
    }
}

function fetchCookies($conn) {
    $sql = "SELECT web FROM cookies";
    $result = $conn->query($sql);

    $cookies = [];
    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            $cookies[] = $row["web"];
        }
    }
    return $cookies;
}

function saveOrUpdateCookies($conn, $data) {
    $selectSql = "SELECT id FROM cookies WHERE web = ?";
    $stmtSelect = $conn->prepare($selectSql);
    $stmtSelect->bind_param("s", $data['web']);
    $stmtSelect->execute();
    $stmtSelect->store_result();

    if ($stmtSelect->num_rows > 0) {
        $updateSql = "UPDATE cookies SET url = ?, cookies = ? WHERE web = ?";
        $stmtUpdate = $conn->prepare($updateSql);
        $stmtUpdate->bind_param("sss", $data['url'], $data['cookies'], $data['web']);

        if ($stmtUpdate->execute()) {
            echo json_encode(['success' => 'Cookies updated successfully']);
        } else {
            echo json_encode(['error' => 'Error updating cookies: ' . $stmtUpdate->error]);
        }
    } else {
        $insertSql = "INSERT INTO cookies (web, url, cookies) VALUES (?, ?, ?)";
        $stmtInsert = $conn->prepare($insertSql);
        $stmtInsert->bind_param("sss", $data['web'], $data['url'], $data['cookies']);
        if ($stmtInsert->execute()) {
            echo json_encode(['success' => 'Cookies saved successfully']);
        } else {
            echo json_encode(['error' => 'Error saving cookies: ' . $stmtInsert->error]);
        }
    }
}

function getCookiesForWebsite($conn, $website) {
    $sql = "SELECT url, cookies FROM cookies WHERE web = ?";  
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $website);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        return json_encode(['url' => $row['url'], 'cookies' => $row['cookies']]); 
    } else {
        return json_encode(['error' => 'No cookies found for this website.']);
    }
}

function handleLogin($conn, $data) {
    $username = $data['username'];
    $password = md5($data['password']); 
    print_r($password);
    $sql = "SELECT * FROM users WHERE username = ? AND password = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ss", $username, $password);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows == 1) {
        session_start();
        $_SESSION['loggedin'] = true; 
        $_SESSION['username'] = $username; 
        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['success' => false]);
    }
}

function handleLogout() {
    session_start(); 
    session_destroy(); 
    header("Location: ../../login.php");
    exit();
}

$conn = connectToDatabase(); 
$tableCheckSql = "SHOW TABLES LIKE 'cookies'";
$tableCheckResult = $conn->query($tableCheckSql);
if ($tableCheckResult->num_rows == 0) {
     createCookiesTable($conn);
}

$tableCheckSql2 = "SHOW TABLES LIKE 'users'";
$tableCheckResult2 = $conn->query($tableCheckSql2);
if ($tableCheckResult2->num_rows == 0) {
     createUsersTable($conn);
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $data = json_decode(file_get_contents("php://input"), true);

    if (isset($_GET['action']) && $_GET['action'] == 'login') {
        handleLogin($conn, $data); 
    } else { 
        saveOrUpdateCookies($conn, $data);
    }
} elseif ($_SERVER['REQUEST_METHOD'] == 'GET') { 
    if (isset($_GET['website'])) { 
        $website = $_GET['website'];
        echo getCookiesForWebsite($conn, $website); 
    } elseif (isset($_GET['action']) && $_GET['action'] == 'logout') {
        handleLogout();
    } else { 
        $cookies = fetchCookies($conn);
        echo json_encode($cookies);
    }
}

$conn->close();
?>
