<?php

function handleGetAllWebsites($method, $pdo)
{
    if ($method !== 'GET') {
        http_response_code(405);
        echo json_encode(['message' => 'Method not allowed']);
        return;
    }

    try {
        // if the url looks like /new-tool/websites, we fetch all websites
        // otherwise, if the url looks like /new-tool/websites?package={package_name}, we fetch websites for that package
        $query = "SELECT * FROM websites w INNER JOIN packages p on w.packages = p.id";
        $params = [];
        if (isset($_GET['packages'])) {
            $package = $_GET['packages'];
            $query .= " WHERE p.package_name = :package";
            $params[':package'] = $package;
        }
        $stmt = $pdo->prepare($query);


        $stmt->execute($params);
        $websites = $stmt->fetchAll(PDO::FETCH_ASSOC);

        if ($websites) {
            http_response_code(200);
            echo json_encode($websites);
        } else {
            http_response_code(404);
            echo json_encode(['message' => 'No websites found']);
        }
    } catch (PDOException $e) {
        http_response_code(500);
        echo json_encode(['message' => 'Database error: ' . $e->getMessage()]);
    }
}

function handlePostWebsite($method, $pdo)
{
    if ($method !== 'POST') {
        http_response_code(405);
        echo json_encode(['message' => 'Method not allowed']);
        return;
    }

    $input = json_decode(file_get_contents('php://input'), true);
    $url = trim($input['url'] ?? '');
    $package = trim((int) $input['package'] ?? '');
    $starting_date = trim($input['starting_date'] ?? '');
    $period = trim((int) $input['period'] ?? '');
    $price = trim((float) $input['price'] ?? '');



    $stmt = $pdo->prepare("INSERT INTO websites (url, packages, starting_date, period, price) VALUES (?, ?, ?, ?, ?)");
    $stmt->execute([$url, $package, $starting_date, $period, $price]);

    $stmt = $pdo->prepare("SELECT *, LAST_INSERT_ID() as id_site  FROM websites w INNER JOIN packages p on w.packages=p.id WHERE w.id = LAST_INSERT_ID()");
    $stmt->execute();
    $website = $stmt->fetch(\PDO::FETCH_ASSOC);

    http_response_code(200); // OK
    echo json_encode([
        "message" => "Insert successful!",
        "website" => [
            "id" => $website['id_site'],
            "url" => $website['url'],
            "packages" => $website['packages'],
            "package_name" => $website['package_name'],
            "starting_date" => $website['starting_date'],
            "period" => $website['period'],
            "price" => $website['price'],
            "name" => $website['name'],
            "image" => $website['image'],
            "color" => $website['color'],
            "price" => $website['price'],
        ],
    ]);
    exit();
}

function handleUpdateWebsite($method, $pdo)
{
    if ($method !== 'PUT') {
        http_response_code(405);
        echo json_encode(['message' => 'Method not allowed.']);
        return;
    }

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

    $url = trim($input['url'] ?? '');
    $websiteId = trim((int) $input['websiteId'] ?? '');


    if (empty($url) || !is_numeric($websiteId)) {
        http_response_code(400);
        echo json_encode(['message' => 'Invalid or missing data for update.']);
        return;
    }

    try {

        $query = "UPDATE websites SET image = :url WHERE id = :websiteId";
        $stmt = $pdo->prepare($query);

        $stmt->bindParam(':url', $url);
        $stmt->bindParam(':websiteId', $websiteId, PDO::PARAM_INT);

        $stmt->execute();

        if ($stmt->rowCount() > 0) {
            http_response_code(200);
            echo json_encode([
                "message" => "Website updated successfully!",
            ]);
        } else {
            http_response_code(404);
            echo json_encode(['message' => 'Website not found or no changes made.']);
        }

    } catch (PDOException $e) {
        http_response_code(500);
        error_log('Database error in handleUpdateWebsite: ' . $e->getMessage());
        echo json_encode(['message' => 'Database error: ' . $e->getMessage()]);
    }
}

function handleGetAllBySearchTerm($method, $pdo)
{
    if ($method !== 'GET') {
        http_response_code(405);
        echo json_encode(['message' => 'Method not allowed']);
        return;
    }

    $searchTerm = isset($_GET['searchTerm']) ? trim($_GET['searchTerm']) : '';
    $query = "SELECT * FROM websites w INNER JOIN packages p on w.packages = p.id";
    $params = [];
    if ($searchTerm) {
        $query .= " WHERE w.url LIKE :searchTerm";
        $params[':searchTerm'] = '%' . $searchTerm . '%';
    }
    $stmt = $pdo->prepare($query);
    $stmt->execute($params);
    $websites = $stmt->fetchAll(PDO::FETCH_ASSOC);
    if ($websites) {
        http_response_code(200);
        echo json_encode($websites);
    } else {
        http_response_code(404);
        echo json_encode(['message' => 'No websites found']);
    }
}

?>