<?php
// apply_discount.php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

header('Content-Type: application/json');
header('Access-Control-Allow-Origin', '*');
header('Access-Control-Allow-Methods', 'POST, OPTIONS');
header('Access-Control-Allow-Headers', 'Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    echo json_encode(['status' => 'ok']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

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

$raw = file_get_contents('php://input');
$data = json_decode($raw, true);

if (!is_array($data)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid JSON payload']);
    exit;
}

$code = strtoupper(trim($data['code'] ?? ''));
$basePrice = $data['basePrice'] ?? null;

if ($code === '') {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Discount code is required.']);
    exit;
}
if ($basePrice === null || !is_numeric($basePrice) || $basePrice <= 0) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Base price is invalid.']);
    exit;
}

try {
    $stmt = $pdo->prepare("SELECT * FROM Discounts WHERE Code = :code LIMIT 1");
    $stmt->execute([':code' => $code]);
    $discount = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$discount) {
        echo json_encode(['success' => false, 'message' => 'Discount code not found.']);
        exit;
    }

    if ((int)$discount['IsActive'] !== 1) {
        echo json_encode(['success' => false, 'message' => 'This discount is not active.']);
        exit;
    }

    $now = new DateTime();
    if (!empty($discount['StartDate'])) {
        $start = new DateTime($discount['StartDate']);
        if ($start > $now) {
            echo json_encode(['success' => false, 'message' => 'Discount not yet active.']);
            exit;
        }
    }
    if (!empty($discount['EndDate'])) {
        $end = new DateTime($discount['EndDate']);
        if ($end < $now) {
            echo json_encode(['success' => false, 'message' => 'Discount has expired.']);
            exit;
        }
    }

    if (!is_null($discount['MaxUses']) && $discount['TimesUsed'] >= $discount['MaxUses']) {
        echo json_encode(['success' => false, 'message' => 'Discount has reached maximum usage.']);
        exit;
    }

    // In DB: Type is 'PERCENTAGE' or 'AMOUNT'
    $type = $discount['Type'];
    $basePrice = (float)$basePrice;
    $discountAmount = 0.0;
    $label = '';

    if (strcasecmp($type, 'PERCENTAGE') === 0) {
        $perc = (float)($discount['PercentageValue'] ?? 0);
        if ($perc <= 0) {
            echo json_encode(['success' => false, 'message' => 'Invalid percentage value.']);
            exit;
        }
        $discountAmount = round($basePrice * ($perc / 100.0), 2);
        $label = "✓ Discount {$perc}% applied successfully!";
    } elseif (strcasecmp($type, 'AMOUNT') === 0) {
        $amt = (float)($discount['AmountValue'] ?? 0);
        if ($amt <= 0) {
            echo json_encode(['success' => false, 'message' => 'Invalid discount amount.']);
            exit;
        }
        $discountAmount = min($amt, $basePrice);
        $label = "✓ Discount ₦" . number_format($discountAmount, 2) . " applied successfully!";
    } else {
        echo json_encode(['success' => false, 'message' => 'Unknown discount type.']);
        exit;
    }

    $finalPrice = max(0, $basePrice - $discountAmount);

    echo json_encode([
        'success'        => true,
        'discountAmount' => $discountAmount,
        'finalPrice'     => $finalPrice,
        'label'          => $label
    ]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Failed to apply discount.',
        'details' => $e->getMessage()
    ]);
}
