<?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);
    $offer = $db->query("SELECT o.*, GROUP_CONCAT(DISTINCT oi.category_id) as applicable_categories, GROUP_CONCAT(DISTINCT oim.menu_item_id) as applicable_items FROM offers o LEFT JOIN offer_categories oi ON o.id = oi.offer_id LEFT JOIN offer_items oim ON o.id = oim.offer_id WHERE o.id = ? AND o.restaurant_id = ? GROUP BY o.id", [$id, $restaurantId])->fetch();
    if ($offer) jsonResponse(true, 'ok', ['offer' => $offer]);
    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['offer_id'] ?? 0);
        $title = trim($_POST['title'] ?? '');
        $description = trim($_POST['description'] ?? '');
        $offerType = $_POST['offer_type'] ?? 'percentage';
        $discountValue = (float)($_POST['discount_value'] ?? 0);
        $couponCode = strtoupper(trim($_POST['coupon_code'] ?? ''));
        $startDate = $_POST['start_date'] ?: null;
        $endDate = $_POST['end_date'] ?: null;
        $startTime = $_POST['start_time'] ?: null;
        $endTime = $_POST['end_time'] ?: null;
        $minOrder = (float)($_POST['min_order'] ?? 0);
        $maxUses = !empty($_POST['max_uses']) ? (int)$_POST['max_uses'] : null;
        $isActive = (int)($_POST['is_active'] ?? 1);
        $selectedCategories = $_POST['selected_categories'] ?? '';
        $selectedItems = $_POST['selected_items'] ?? '';

        if (empty($title)) jsonResponse(false, 'Title is required');
        if ($discountValue <= 0) jsonResponse(false, 'Discount value must be greater than 0');

        $upload = new Upload();
        $bannerImage = null;
        if (!empty($_FILES['banner_image']['name'])) {
            $result = $upload->uploadFile($_FILES['banner_image'], 'offers/' . $restaurantId);
            if ($result['success']) {
                $bannerImage = $result['path'];
            } else {
                jsonResponse(false, 'Banner image upload failed: ' . implode(', ', $result['errors']));
            }
        }

        $slug = slugify($title);
        $offerData = [
            'restaurant_id' => $restaurantId,
            'title' => $title,
            'slug' => $slug,
            'description' => $description,
            'offer_type' => $offerType,
            'discount_value' => $discountValue,
            'coupon_code' => $couponCode ?: null,
            'start_date' => $startDate,
            'end_date' => $endDate,
            'start_time' => $startTime,
            'end_time' => $endTime,
            'min_order' => $minOrder,
            'max_uses' => $maxUses,
            'is_active' => $isActive,
        ];
        if ($bannerImage) $offerData['banner_image'] = $bannerImage;

        if ($action === 'add') {
            $offerId = $db->insert('offers', $offerData);
        } else {
            $existing = $db->query("SELECT id FROM offers WHERE id = ? AND restaurant_id = ?", [$id, $restaurantId])->fetch();
            if (!$existing) jsonResponse(false, 'Offer not found');
            $db->update('offers', $offerData, 'id = ?', [$id]);
            $offerId = $id;
            $db->delete('offer_items', 'offer_id = ?', [$offerId]);
            $db->delete('offer_categories', 'offer_id = ?', [$offerId]);
        }

        if ($selectedCategories) {
            $cats = array_map('intval', explode(',', $selectedCategories));
            foreach ($cats as $catId) {
                if ($catId > 0) {
                    $db->insert('offer_categories', ['offer_id' => $offerId, 'category_id' => $catId]);
                }
            }
        }
        if ($selectedItems) {
            $items = array_map('intval', explode(',', $selectedItems));
            foreach ($items as $itemId) {
                if ($itemId > 0) {
                    $db->insert('offer_items', ['offer_id' => $offerId, 'menu_item_id' => $itemId]);
                }
            }
        }

        jsonResponse(true, 'Offer ' . ($action === 'add' ? 'created' : 'updated') . ' successfully');
    }

    if ($action === 'delete') {
        $id = (int)($_POST['id'] ?? 0);
        $offer = $db->query("SELECT id, title FROM offers WHERE id = ? AND restaurant_id = ?", [$id, $restaurantId])->fetch();
        if (!$offer) jsonResponse(false, 'Offer not found');
        $db->delete('offers', 'id = ? AND restaurant_id = ?', [$id, $restaurantId]);
        jsonResponse(true, 'Offer deleted');
    }

    if ($action === 'toggle_status') {
        $id = (int)($_POST['id'] ?? 0);
        $offer = $db->query("SELECT id, is_active FROM offers WHERE id = ? AND restaurant_id = ?", [$id, $restaurantId])->fetch();
        if (!$offer) jsonResponse(false, 'Offer not found');
        $newStatus = $offer['is_active'] ? 0 : 1;
        $db->update('offers', ['is_active' => $newStatus], 'id = ?', [$id]);
        jsonResponse(true, 'Offer ' . ($newStatus ? 'activated' : 'deactivated'));
    }
}

jsonResponse(false, 'Invalid request');
