<?php
session_start();
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/config.php';

header('Content-Type: application/json; charset=utf-8');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    jsonResponse(false, 'Method not allowed', [], 405);
}

$input = json_decode(file_get_contents('php://input'), true);
if (!$input) {
    jsonResponse(false, 'Invalid request');
}

$restaurantId = (int) ($input['restaurant_id'] ?? 0);
$promoCode = strtoupper(trim($input['promo_code'] ?? ''));
$subtotal = (float) ($input['subtotal'] ?? 0);

if ($restaurantId <= 0) {
    jsonResponse(false, 'Invalid restaurant');
}
if (empty($promoCode)) {
    jsonResponse(false, 'Please enter a promo code');
}

$db = Database::getInstance();

$offer = $db->query(
    "SELECT * FROM offers WHERE restaurant_id = ? AND coupon_code = ? AND is_active = 1",
    [$restaurantId, $promoCode]
)->fetch();

if (!$offer) {
    jsonResponse(false, 'Invalid promo code');
}

if (!empty($offer['start_date']) && $offer['start_date'] > date('Y-m-d')) {
    jsonResponse(false, 'This promo code is not yet active');
}
if (!empty($offer['end_date']) && $offer['end_date'] < date('Y-m-d')) {
    jsonResponse(false, 'This promo code has expired');
}

if (!empty($offer['start_time']) && !empty($offer['end_time'])) {
    $now = date('H:i:s');
    if ($now < $offer['start_time'] || $now > $offer['end_time']) {
        jsonResponse(false, 'This promo code is not valid at this time');
    }
}

$minOrder = (float) ($offer['min_order'] ?? 0);
if ($minOrder > 0 && $subtotal < $minOrder) {
    jsonResponse(false, 'Minimum order amount for this code is ' . formatCurrency($minOrder));
}

$discountType = $offer['offer_type'] ?? 'fixed';
$discountValue = (float) $offer['discount_value'];

if ($discountType === 'percentage') {
    $discountAmount = round($subtotal * ($discountValue / 100), 2);
} else {
    $discountAmount = min($discountValue, $subtotal);
}

jsonResponse(true, 'Promo code applied successfully', [
    'discount_type'   => $discountType,
    'discount_value'  => $discountValue,
    'discount_amount' => $discountAmount,
    'offer_title'     => $offer['title'] ?? '',
]);
