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

require_once __DIR__ . '/../config/db.php';

function ensureServicesTable(mysqli $connection): bool
{
    $sql = "CREATE TABLE IF NOT EXISTS services (
        id INT AUTO_INCREMENT PRIMARY KEY,
        title VARCHAR(255) NOT NULL,
        image VARCHAR(500) NOT NULL,
        link VARCHAR(500) DEFAULT '#',
        description TEXT NOT NULL,
        sort_order INT NOT NULL DEFAULT 0,
        is_active TINYINT(1) NOT NULL DEFAULT 1,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";

    if (!$connection->query($sql)) {
        return false;
    }

    $requiredColumns = [
        'title' => "ALTER TABLE services ADD COLUMN title VARCHAR(255) NOT NULL DEFAULT ''",
        'image' => "ALTER TABLE services ADD COLUMN image VARCHAR(500) NOT NULL DEFAULT ''",
        'link' => "ALTER TABLE services ADD COLUMN link VARCHAR(500) DEFAULT '#'",
        'description' => "ALTER TABLE services ADD COLUMN description TEXT NOT NULL",
        'sort_order' => "ALTER TABLE services ADD COLUMN sort_order INT NOT NULL DEFAULT 0",
        'is_active' => "ALTER TABLE services ADD COLUMN is_active TINYINT(1) NOT NULL DEFAULT 1",
        'created_at' => "ALTER TABLE services ADD COLUMN created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP",
        'updated_at' => "ALTER TABLE services ADD COLUMN updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP",
    ];

    $existingColumns = [];
    $columnsResult = $connection->query("SHOW COLUMNS FROM services");
    if ($columnsResult) {
        while ($column = $columnsResult->fetch_assoc()) {
            $existingColumns[] = $column['Field'];
        }
    }

    foreach ($requiredColumns as $columnName => $alterSql) {
        if (!in_array($columnName, $existingColumns, true)) {
            if (!$connection->query($alterSql)) {
                return false;
            }
        }
    }

    return true;
}

function syncServicesFromHtmlIfEmpty(mysqli $connection, string $serviceFile): void
{
    $countResult = $connection->query("SELECT COUNT(*) AS total FROM services");
    $row = $countResult ? $countResult->fetch_assoc() : ['total' => 0];
    $total = (int) ($row['total'] ?? 0);

    if ($total > 0 || !file_exists($serviceFile)) {
        return;
    }

    $html = file_get_contents($serviceFile);
    if ($html === false) {
        return;
    }

    $pattern = '/<div class="col-md-6 col-xl-4">\s*<div class="service-box[^>]*>\s*<div class="box-img[^>]*><img src="([^"]+)"[^>]*><\/div>\s*<div class="box-content">\s*<h3 class="box-title"><a href="([^"]*)">([^<]+)<\/a><\/h3>\s*<p class="box-text">\s*(.*?)\s*<\/p>/si';

    if (!preg_match_all($pattern, $html, $matches, PREG_SET_ORDER)) {
        return;
    }

    $insert = $connection->prepare("INSERT INTO services (title, image, link, description, sort_order, is_active) VALUES (?, ?, ?, ?, ?, 1)");
    if (!$insert) {
        return;
    }

    foreach ($matches as $index => $item) {
        $image = trim(html_entity_decode($item[1], ENT_QUOTES | ENT_HTML5, 'UTF-8'));
        $link = trim(html_entity_decode($item[2], ENT_QUOTES | ENT_HTML5, 'UTF-8'));
        $title = trim(html_entity_decode($item[3], ENT_QUOTES | ENT_HTML5, 'UTF-8'));
        $description = trim(strip_tags(html_entity_decode($item[4], ENT_QUOTES | ENT_HTML5, 'UTF-8')));
        $sortOrder = $index + 1;

        if ($title === '' || $image === '' || $description === '') {
            continue;
        }

        $insert->bind_param('ssssi', $title, $image, $link, $description, $sortOrder);
        $insert->execute();
    }

    $insert->close();
}

function getServiceByIndex(mysqli $connection, int $serviceIndex): ?array
{
    $stmt = $connection->prepare("SELECT id, link FROM services ORDER BY sort_order ASC, id ASC LIMIT 1 OFFSET ?");
    if (!$stmt) {
        return null;
    }

    $stmt->bind_param('i', $serviceIndex);
    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result ? $result->fetch_assoc() : null;
    $stmt->close();

    return $row ?: null;
}

if (!isset($_SESSION['user_role']) || $_SESSION['user_role'] !== 'admin') {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit;
}

$action = $_POST['action'] ?? '';
$serviceFile = __DIR__ . '/../service.html';

if (!ensureServicesTable($connection)) {
    echo json_encode(['success' => false, 'message' => 'Failed to prepare services table']);
    exit;
}

syncServicesFromHtmlIfEmpty($connection, $serviceFile);

if ($action === 'add_service') {
    $title = trim($_POST['title'] ?? '');
    $image = trim($_POST['image'] ?? '');
    $link = trim($_POST['link'] ?? '#');
    $description = trim($_POST['description'] ?? '');

    if ($title === '' || $image === '' || $description === '') {
        echo json_encode(['success' => false, 'message' => 'Missing required fields']);
        exit;
    }

    $maxResult = $connection->query("SELECT COALESCE(MAX(sort_order), 0) AS max_order FROM services");
    $maxRow = $maxResult ? $maxResult->fetch_assoc() : ['max_order' => 0];
    $nextOrder = ((int) ($maxRow['max_order'] ?? 0)) + 1;

    $insert = $connection->prepare("INSERT INTO services (title, image, link, description, sort_order, is_active) VALUES (?, ?, ?, ?, ?, 1)");
    if (!$insert) {
        echo json_encode(['success' => false, 'message' => 'Failed to prepare DB insert']);
        exit;
    }

    $insert->bind_param('ssssi', $title, $image, $link, $description, $nextOrder);
    $saved = $insert->execute();
    $insert->close();

    echo json_encode(['success' => $saved, 'message' => $saved ? 'Service added successfully' : 'Failed to save service in database']);
    exit;
}

if ($action === 'update_service') {
    $serviceIndex = intval($_POST['service_index'] ?? -1);
    $title = trim($_POST['title'] ?? '');
    $image = trim($_POST['image'] ?? '');
    $link = trim($_POST['link'] ?? '');
    $description = trim($_POST['description'] ?? '');

    if ($serviceIndex < 0 || $title === '' || $image === '' || $description === '') {
        echo json_encode(['success' => false, 'message' => 'Missing required fields']);
        exit;
    }

    $service = getServiceByIndex($connection, $serviceIndex);
    if (!$service) {
        echo json_encode(['success' => false, 'message' => 'Service index out of range']);
        exit;
    }

    $serviceId = (int) $service['id'];
    $finalLink = $link !== '' ? $link : ((string) ($service['link'] ?? '#'));

    $update = $connection->prepare("UPDATE services SET title = ?, image = ?, link = ?, description = ? WHERE id = ?");
    if (!$update) {
        echo json_encode(['success' => false, 'message' => 'Failed to prepare DB update']);
        exit;
    }

    $update->bind_param('ssssi', $title, $image, $finalLink, $description, $serviceId);
    $updated = $update->execute();
    $update->close();

    echo json_encode(['success' => $updated, 'message' => $updated ? 'Service updated successfully' : 'Failed to update service in database']);
    exit;
}

echo json_encode(['success' => false, 'message' => 'Invalid action']);
