<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

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

$auth = new Auth();
$auth->requireRole(['restaurant_admin', 'restaurant_manager', 'cashier', 'kitchen_staff', 'waiter']);

$csrf = new CSRF();
$restaurantId = $auth->restaurantId();
$userId = $auth->userId();
$db = Database::getInstance();

$action = $_GET['action'] ?? $_POST['action'] ?? '';
$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET' && $action === 'get') {
    $id = (int)($_GET['id'] ?? 0);
    $ad = $db->query("SELECT * FROM advertisements WHERE id = ? AND restaurant_id = ?", [$id, $restaurantId])->fetch();
    if ($ad) jsonResponse(true, 'ok', ['ad' => $ad]);
    jsonResponse(false, 'Not found');
}

if ($method === 'POST') {
    if (empty($_POST['csrf_token']) || !$csrf->verify($_POST['csrf_token'])) {
        jsonResponse(false, 'Invalid CSRF token');
    }

    if ($action === 'add' || $action === 'edit') {
        $id = (int)($_POST['ad_id'] ?? 0);
        $title = trim($_POST['title'] ?? '');
        $description = trim($_POST['description'] ?? '');
        $position = $_POST['position'] ?? 'top_banner';
        $buttonText = trim($_POST['button_text'] ?? '');
        $buttonLink = trim($_POST['button_link'] ?? '');
        $startDate = $_POST['start_date'] ?: null;
        $endDate = $_POST['end_date'] ?: null;
        $displayFrequency = $_POST['display_frequency'] ?? 'always';
        $isActive = (int)($_POST['is_active'] ?? 1);

        if (empty($position)) jsonResponse(false, 'Position is required');

        $upload = new Upload();
        $image = null;
        $mobileImage = null;

        if (!empty($_FILES['image']['name'])) {
            $result = $upload->uploadFile($_FILES['image'], 'ads/' . $restaurantId);
            if ($result['success']) {
                $image = $result['path'];
            } else {
                jsonResponse(false, 'Image upload failed: ' . implode(', ', $result['errors']));
            }
        }
        if (!empty($_FILES['mobile_image']['name'])) {
            $result = $upload->uploadFile($_FILES['mobile_image'], 'ads/' . $restaurantId);
            if ($result['success']) {
                $mobileImage = $result['path'];
            } else {
                jsonResponse(false, 'Mobile image upload failed: ' . implode(', ', $result['errors']));
            }
        }

        $adData = [
            'restaurant_id' => $restaurantId,
            'title' => $title,
            'description' => $description,
            'position' => $position,
            'button_text' => $buttonText,
            'button_link' => $buttonLink,
            'start_date' => $startDate,
            'end_date' => $endDate,
            'display_frequency' => $displayFrequency,
            'is_active' => $isActive,
        ];
        if ($image) $adData['image'] = $image;
        if ($mobileImage) $adData['mobile_image'] = $mobileImage;

        if ($action === 'add') {
            $db->insert('advertisements', $adData);
            jsonResponse(true, 'Advertisement created');
        } else {
            $existing = $db->query("SELECT id FROM advertisements WHERE id = ? AND restaurant_id = ?", [$id, $restaurantId])->fetch();
            if (!$existing) jsonResponse(false, 'Not found');
            $db->update('advertisements', $adData, 'id = ?', [$id]);
            jsonResponse(true, 'Advertisement updated');
        }
    }

    if ($action === 'delete') {
        $id = (int)($_POST['id'] ?? 0);
        $db->delete('advertisements', 'id = ? AND restaurant_id = ?', [$id, $restaurantId]);
        jsonResponse(true, 'Advertisement deleted');
    }

    if ($action === 'toggle_status') {
        $id = (int)($_POST['id'] ?? 0);
        $ad = $db->query("SELECT id, is_active FROM advertisements WHERE id = ? AND restaurant_id = ?", [$id, $restaurantId])->fetch();
        if (!$ad) jsonResponse(false, 'Not found');
        $newStatus = $ad['is_active'] ? 0 : 1;
        $db->update('advertisements', ['is_active' => $newStatus], 'id = ?', [$id]);
        jsonResponse(true, 'Status updated');
    }
}

jsonResponse(false, 'Invalid request');
