<?php
/**
 * Hero Slider Management Handler (DB-backed)
 */
session_start();
header('Content-Type: application/json');

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

$response = [
    'success' => false,
    'message' => '',
    'data' => null,
];

if (!isset($_SESSION['user_id']) || ($_SESSION['user_role'] ?? '') !== 'admin') {
    $response['message'] = 'Unauthorized access';
    echo json_encode($response);
    exit;
}

if (!isset($_POST['action'])) {
    $response['message'] = 'No action specified';
    echo json_encode($response);
    exit;
}

function ensureHeroSlidesTable(mysqli $connection): bool
{
    $sql = "CREATE TABLE IF NOT EXISTS hero_slides (
        id INT AUTO_INCREMENT PRIMARY KEY,
        image VARCHAR(500) NOT NULL,
        subtitle VARCHAR(255) NOT NULL DEFAULT 'Innovative solutions',
        title_part1 VARCHAR(500) NOT NULL,
        highlight VARCHAR(255) NOT NULL,
        title_part2 VARCHAR(500) NOT NULL DEFAULT '',
        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 = [
        'image' => "ALTER TABLE hero_slides ADD COLUMN image VARCHAR(500) NOT NULL DEFAULT ''",
        'subtitle' => "ALTER TABLE hero_slides ADD COLUMN subtitle VARCHAR(255) NOT NULL DEFAULT 'Innovative solutions'",
        'title_part1' => "ALTER TABLE hero_slides ADD COLUMN title_part1 VARCHAR(500) NOT NULL DEFAULT ''",
        'highlight' => "ALTER TABLE hero_slides ADD COLUMN highlight VARCHAR(255) NOT NULL DEFAULT ''",
        'title_part2' => "ALTER TABLE hero_slides ADD COLUMN title_part2 VARCHAR(500) NOT NULL DEFAULT ''",
        'sort_order' => "ALTER TABLE hero_slides ADD COLUMN sort_order INT NOT NULL DEFAULT 0",
        'is_active' => "ALTER TABLE hero_slides ADD COLUMN is_active TINYINT(1) NOT NULL DEFAULT 1",
        'created_at' => "ALTER TABLE hero_slides ADD COLUMN created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP",
        'updated_at' => "ALTER TABLE hero_slides ADD COLUMN updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP",
    ];

    $existingColumns = [];
    $colsResult = $connection->query("SHOW COLUMNS FROM hero_slides");
    if ($colsResult) {
        while ($col = $colsResult->fetch_assoc()) {
            $existingColumns[] = $col['Field'];
        }
    }

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

    return true;
}

function normalizeHeroSlideOrder(mysqli $connection): void
{
    $result = $connection->query("SELECT id FROM hero_slides WHERE is_active = 1 ORDER BY sort_order ASC, id ASC");
    if (!$result) {
        return;
    }

    $update = $connection->prepare("UPDATE hero_slides SET sort_order = ? WHERE id = ?");
    if (!$update) {
        return;
    }

    $order = 1;
    while ($row = $result->fetch_assoc()) {
        $id = (int)$row['id'];
        $sortOrder = $order++;
        $update->bind_param('ii', $sortOrder, $id);
        $update->execute();
    }

    $update->close();
}

function getHeroSlidesFromDb(mysqli $connection): array
{
    $slides = [];
    $result = $connection->query("SELECT id, image, subtitle, title_part1, highlight, title_part2 FROM hero_slides WHERE is_active = 1 ORDER BY sort_order ASC, id ASC");
    if (!$result) {
        return $slides;
    }

    $index = 0;
    while ($row = $result->fetch_assoc()) {
        $row['index'] = $index++;
        $slides[] = $row;
    }

    return $slides;
}

function splitTitleParts(string $title, string $highlight): array
{
    $title = trim($title);
    $highlight = trim($highlight);

    if ($title === '' || $highlight === '') {
        return [$title, '', ''];
    }

    $pos = stripos($title, $highlight);
    if ($pos === false) {
        return [$title, $highlight, ''];
    }

    $part1 = trim(substr($title, 0, $pos));
    $part2 = trim(substr($title, $pos + strlen($highlight)));

    return [$part1, $highlight, $part2];
}

function getSlideIdByIndex(mysqli $connection, int $slideIndex): ?int
{
    $stmt = $connection->prepare("SELECT id FROM hero_slides WHERE is_active = 1 ORDER BY sort_order ASC, id ASC LIMIT 1 OFFSET ?");
    if (!$stmt) {
        return null;
    }

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

    return $row ? (int)$row['id'] : null;
}

if (!ensureHeroSlidesTable($connection)) {
    $response['message'] = 'Failed to prepare hero slides table';
    echo json_encode($response);
    exit;
}

$action = $_POST['action'];

switch ($action) {
    case 'get_slides':
        $response['success'] = true;
        $response['data'] = getHeroSlidesFromDb($connection);
        break;

    case 'add_slide':
        $image = trim((string)($_POST['image'] ?? ''));
        $title = trim((string)($_POST['title'] ?? ''));
        $highlight = trim((string)($_POST['highlight'] ?? ''));
        $subtitle = trim((string)($_POST['subtitle'] ?? 'Innovative solutions'));

        if ($image === '' || $title === '' || $highlight === '') {
            $response['message'] = 'Missing required fields';
            break;
        }

        [$part1, $hl, $part2] = splitTitleParts($title, $highlight);

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

        $stmt = $connection->prepare("INSERT INTO hero_slides (image, subtitle, title_part1, highlight, title_part2, sort_order, is_active) VALUES (?, ?, ?, ?, ?, ?, 1)");
        if (!$stmt) {
            $response['message'] = 'Failed to prepare insert';
            break;
        }

        $stmt->bind_param('sssssi', $image, $subtitle, $part1, $hl, $part2, $nextOrder);
        $ok = $stmt->execute();
        $stmt->close();

        $response['success'] = (bool)$ok;
        $response['message'] = $ok ? 'Slide added successfully!' : 'Failed to add slide';
        $response['data'] = getHeroSlidesFromDb($connection);
        break;

    case 'edit_slide':
        $slideIndex = (int)($_POST['slide_index'] ?? -1);
        $image = trim((string)($_POST['image'] ?? ''));
        $title = trim((string)($_POST['title'] ?? ''));
        $highlight = trim((string)($_POST['highlight'] ?? ''));
        $subtitle = trim((string)($_POST['subtitle'] ?? 'Innovative solutions'));

        if ($slideIndex < 0 || $image === '' || $title === '' || $highlight === '') {
            $response['message'] = 'Missing required fields';
            break;
        }

        $slideId = getSlideIdByIndex($connection, $slideIndex);
        if ($slideId === null) {
            $response['message'] = 'Slide not found';
            break;
        }

        [$part1, $hl, $part2] = splitTitleParts($title, $highlight);

        $stmt = $connection->prepare("UPDATE hero_slides SET image = ?, subtitle = ?, title_part1 = ?, highlight = ?, title_part2 = ? WHERE id = ?");
        if (!$stmt) {
            $response['message'] = 'Failed to prepare update';
            break;
        }

        $stmt->bind_param('sssssi', $image, $subtitle, $part1, $hl, $part2, $slideId);
        $ok = $stmt->execute();
        $stmt->close();

        $response['success'] = (bool)$ok;
        $response['message'] = $ok ? 'Slide updated successfully!' : 'Failed to update slide';
        $response['data'] = getHeroSlidesFromDb($connection);
        break;

    case 'delete_slide':
        $slideIndex = (int)($_POST['slide_index'] ?? -1);
        if ($slideIndex < 0) {
            $response['message'] = 'Invalid slide index';
            break;
        }

        $slides = getHeroSlidesFromDb($connection);
        if (count($slides) <= 1) {
            $response['message'] = 'Cannot delete the last slide';
            break;
        }

        $slideId = getSlideIdByIndex($connection, $slideIndex);
        if ($slideId === null) {
            $response['message'] = 'Slide not found';
            break;
        }

        $stmt = $connection->prepare("DELETE FROM hero_slides WHERE id = ?");
        if (!$stmt) {
            $response['message'] = 'Failed to prepare delete';
            break;
        }

        $stmt->bind_param('i', $slideId);
        $ok = $stmt->execute();
        $stmt->close();

        if ($ok) {
            normalizeHeroSlideOrder($connection);
        }

        $response['success'] = (bool)$ok;
        $response['message'] = $ok ? 'Slide deleted successfully!' : 'Failed to delete slide';
        $response['data'] = getHeroSlidesFromDb($connection);
        break;

    default:
        $response['message'] = 'Unknown action: ' . $action;
}

echo json_encode($response);
?>
