<?php
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../config/constants.php';
require_once __DIR__ . '/../../includes/functions.php';
require_once __DIR__ . '/../../includes/auth_admin.php';
require_once __DIR__ . '/../../includes/audit.php';
require_once __DIR__ . '/../../includes/upload.php';

apply_cors();
$admin = require_admin();
$pdo = getDbConnection();
$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';

// GET    /banners.php               -> list all (admin view, includes inactive)
// POST   /banners.php               -> create (multipart with image file)
// PUT    /banners.php?id=5          -> update fields
// PATCH  /banners.php?id=5&action=status  -> enable/disable
// PATCH  /banners.php?action=reorder      -> { order: [id1, id2, id3] }
// DELETE /banners.php?id=5          -> delete

if ($method === 'GET') {
    $stmt = $pdo->query('SELECT * FROM banners ORDER BY display_order ASC, created_at DESC');
    send_success(['banners' => $stmt->fetchAll()]);
}

if ($method === 'POST') {
    $isMultipart = str_starts_with($_SERVER['CONTENT_TYPE'] ?? '', 'multipart/form-data');
    $input = $isMultipart ? $_POST : get_json_input();
    require_fields($input, ['title']);

    $imageUrl = clean_str($input['image_url'] ?? '');
    if ($isMultipart && isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
        $imageUrl = handle_file_upload('image', 'banners', ALLOWED_IMAGE_TYPES);
    }
    if ($imageUrl === '') {
        send_error('Banner image is required (upload a file or provide image_url).', 422);
    }

    $maxOrder = (int) $pdo->query('SELECT COALESCE(MAX(display_order),0) FROM banners')->fetchColumn();

    $stmt = $pdo->prepare(
        'INSERT INTO banners (title, description, image_url, button_text, button_url, start_date, end_date, is_active, display_order)
         VALUES (:title, :description, :image_url, :button_text, :button_url, :start_date, :end_date, :is_active, :display_order)'
    );
    $stmt->execute([
        ':title'       => clean_str($input['title']),
        ':description' => clean_str($input['description'] ?? ''),
        ':image_url'   => $imageUrl,
        ':button_text' => clean_str($input['button_text'] ?? 'Learn More'),
        ':button_url'  => clean_str($input['button_url'] ?? ''),
        ':start_date'  => !empty($input['start_date']) ? $input['start_date'] : null,
        ':end_date'    => !empty($input['end_date']) ? $input['end_date'] : null,
        ':is_active'   => isset($input['is_active']) ? (int) (bool) $input['is_active'] : 1,
        ':display_order' => $maxOrder + 1,
    ]);

    $newId = (int) $pdo->lastInsertId();
    log_admin_action($admin['email'], 'CREATE_BANNER', 'banner_id:' . $newId, '');
    send_success(['banner_id' => $newId], 'Banner created.', 201);
}

if ($method === 'PUT' && isset($_GET['id'])) {
    $id = (int) $_GET['id'];
    $input = get_json_input();

    $allowed = ['title', 'description', 'image_url', 'button_text', 'button_url', 'start_date', 'end_date'];
    $fields = [];
    $params = [':id' => $id];
    foreach ($allowed as $f) {
        if (isset($input[$f])) {
            $fields[] = "$f = :$f";
            $params[":$f"] = $input[$f] === '' && in_array($f, ['start_date', 'end_date'], true) ? null : clean_str($input[$f]);
        }
    }
    if (empty($fields)) send_error('No fields to update.', 422);

    $stmt = $pdo->prepare('UPDATE banners SET ' . implode(', ', $fields) . ' WHERE id = :id');
    $stmt->execute($params);

    log_admin_action($admin['email'], 'UPDATE_BANNER', 'banner_id:' . $id, '');
    send_success(null, 'Banner updated.');
}

if ($method === 'PATCH' && $action === 'reorder') {
    $input = get_json_input();
    require_fields($input, ['order']);

    $stmt = $pdo->prepare('UPDATE banners SET display_order = :pos WHERE id = :id');
    foreach ($input['order'] as $position => $bannerId) {
        $stmt->execute([':pos' => $position, ':id' => (int) $bannerId]);
    }

    log_admin_action($admin['email'], 'REORDER_BANNERS', '', json_encode($input['order']));
    send_success(null, 'Banner order updated.');
}

if ($method === 'PATCH' && isset($_GET['id']) && $action === 'status') {
    $id = (int) $_GET['id'];
    $input = get_json_input();
    require_fields($input, ['is_active']);

    $stmt = $pdo->prepare('UPDATE banners SET is_active = :active WHERE id = :id');
    $stmt->execute([':active' => $input['is_active'] ? 1 : 0, ':id' => $id]);

    log_admin_action($admin['email'], 'TOGGLE_BANNER', 'banner_id:' . $id, '');
    send_success(null, 'Banner status updated.');
}

if ($method === 'DELETE' && isset($_GET['id'])) {
    $stmt = $pdo->prepare('DELETE FROM banners WHERE id = :id');
    $stmt->execute([':id' => (int) $_GET['id']]);

    log_admin_action($admin['email'], 'DELETE_BANNER', 'banner_id:' . $_GET['id'], '');
    send_success(null, 'Banner deleted.');
}

send_error('Invalid request.', 400);
