<?php
// =====================
// SESSION MUST BE FIRST
// =====================
session_start();

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

$allowed_origin = $_SERVER['HTTP_ORIGIN'] ?? '';
if (preg_match('/^https:\/\/([a-z0-9-]+\.)?aiitsolution\.com$/', $allowed_origin)) {
    header("Access-Control-Allow-Origin: $allowed_origin");
}
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");

// =====================
// DATABASE CONFIG
// =====================
$servername = "localhost";
$username   = "aiitsolu_amirdeveloper";
$password   = "5xXCK=VT0ZmL-A?^";
$dbname     = "aiitsolu_cookies";

// =====================
// DATABASE CONNECT
// =====================
function connectToDatabase() {
    global $servername, $username, $password, $dbname;

    $conn = new mysqli($servername, $username, $password, $dbname);
    if ($conn->connect_error) {
        echo json_encode(['error' => 'DB connection failed']);
        exit;
    }
    return $conn;
}

// =====================
// TABLES
// =====================
function createUsersTable($conn) {
    $sql = "CREATE TABLE IF NOT EXISTS users (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(50),
        username VARCHAR(50) UNIQUE,
        password VARCHAR(255)
    )";
    $conn->query($sql);
}

function createCookiesTable($conn) {
    $sql = "CREATE TABLE IF NOT EXISTS cookies (
        id INT AUTO_INCREMENT PRIMARY KEY,
        web VARCHAR(30) UNIQUE NOT NULL,
        url VARCHAR(255) NOT NULL,
        cookies TEXT NOT NULL
    )";
    $conn->query($sql);
}

// =====================
// LOGIN
// =====================
function handleLogin($conn, $data) {
    $username = $data['username'] ?? '';
    $password = md5($data['password'] ?? '');

    $sql = "SELECT id FROM users WHERE username=? AND password=?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ss", $username, $password);
    $stmt->execute();
    $res = $stmt->get_result();

    if ($res && $res->num_rows === 1) {
        $_SESSION['loggedin'] = true;
        $_SESSION['username'] = $username;

        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['success' => false]);
    }
}

// =====================
// LOGOUT
// =====================
function handleLogout() {
    session_destroy();
    echo json_encode(['success' => true]);
    exit;
}

// =====================
// COOKIES CRUD
// =====================
function fetchCookies($conn) {
    $res = $conn->query("SELECT web FROM cookies");
    $data = [];
    while ($row = $res->fetch_assoc()) {
        $data[] = $row['web'];
    }
    echo json_encode($data);
}

function saveOrUpdateCookies($conn, $data) {
    $sql = "INSERT INTO cookies (web, url, cookies)
            VALUES (?, ?, ?)
            ON DUPLICATE KEY UPDATE
            url=VALUES(url), cookies=VALUES(cookies)";

    $stmt = $conn->prepare($sql);
    $stmt->bind_param("sss", $data['web'], $data['url'], $data['cookies']);
    $stmt->execute();

    echo json_encode(['success' => true]);
}

function getCookiesForWebsite($conn, $website) {
    $stmt = $conn->prepare("SELECT url, cookies FROM cookies WHERE web=?");
    $stmt->bind_param("s", $website);
    $stmt->execute();
    $res = $stmt->get_result();

    if ($res->num_rows === 1) {
        echo json_encode($res->fetch_assoc());
    } else {
        echo json_encode(['error' => 'Not found']);
    }
}

// =====================
// MAIN
// =====================
$conn = connectToDatabase();
createUsersTable($conn);
createCookiesTable($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['action']) && $_GET['action'] === 'logout') {
        handleLogout();
    } elseif (isset($_GET['website'])) {
        getCookiesForWebsite($conn, $_GET['website']);
    } else {
        fetchCookies($conn);
    }
}

$conn->close();
