<?php
declare(strict_types=1);
if (session_status() === PHP_SESSION_NONE) session_start();
require_once __DIR__ . '/../config.php';

header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']); exit;
}

$conn   = getDBConnection();
$action = trim((string) ($_POST['action'] ?? $_GET['action'] ?? ''));
$userId = (int) $_SESSION['user_id'];
$role   = $_SESSION['role'] ?? '';

if (!$conn instanceof mysqli) {
    echo json_encode(['success' => false, 'message' => 'Database unavailable']); exit;
}

switch ($action) {

    // ── GET ALL ────────────────────────────────────────────────────────────
    case 'get_all':
        $stmt = $conn->prepare(
            "SELECT c.*,
                    COALESCE(u.full_name,'') AS created_by_name,
                    (SELECT COUNT(*) FROM coupon_usages cu WHERE cu.coupon_id = c.id) AS usage_count
             FROM coupons c
             LEFT JOIN users u ON u.id = c.created_by
             ORDER BY c.created_at DESC"
        );
        $stmt->execute();
        $rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        $stmt->close();
        echo json_encode($rows);
        break;

    // ── SAVE (INSERT or UPDATE) ────────────────────────────────────────────
    case 'save':
        if (!in_array($role, ['admin', 'headteacher', 'accountant'], true)) {
            echo json_encode(['success' => false, 'message' => 'Insufficient permissions']); break;
        }

        $id             = (int) ($_POST['id'] ?? 0);
        $coupon_code    = strtoupper(trim((string) ($_POST['coupon_code'] ?? '')));
        $coupon_name    = trim((string) ($_POST['coupon_name'] ?? ''));
        $discount_type  = in_array($_POST['discount_type'] ?? '', ['percentage','fixed']) ? $_POST['discount_type'] : 'percentage';
        $discount_value = floatval($_POST['discount_value'] ?? 0);
        $max_uses       = ($_POST['max_uses'] ?? '') !== '' ? (int) $_POST['max_uses'] : null;
        $applicable_to  = in_array($_POST['applicable_to'] ?? '', ['all','specific_class','specific_fee']) ? $_POST['applicable_to'] : 'all';
        $applicable_class   = trim((string) ($_POST['applicable_class'] ?? ''));
        $applicable_fee_id  = (int) ($_POST['applicable_fee_id'] ?? 0) ?: null;
        $valid_from     = trim((string) ($_POST['valid_from'] ?? '')) ?: null;
        $valid_until    = trim((string) ($_POST['valid_until'] ?? ''));
        $is_active      = isset($_POST['is_active']) ? 1 : 0;

        if (empty($coupon_code) || empty($coupon_name) || $discount_value <= 0 || empty($valid_until)) {
            echo json_encode(['success' => false, 'message' => 'Please fill all required fields']); break;
        }
        if ($discount_type === 'percentage' && $discount_value > 100) {
            echo json_encode(['success' => false, 'message' => 'Percentage discount cannot exceed 100%']); break;
        }
        if (strtotime($valid_until) < strtotime(date('Y-m-d'))) {
            echo json_encode(['success' => false, 'message' => 'Valid until date must be in the future']); break;
        }

        if ($id === 0) {
            // Check uniqueness
            $chk = $conn->prepare("SELECT id FROM coupons WHERE coupon_code = ?");
            $chk->bind_param('s', $coupon_code);
            $chk->execute();
            if ($chk->get_result()->num_rows > 0) {
                $chk->close();
                echo json_encode(['success' => false, 'message' => 'Coupon code already exists']); break;
            }
            $chk->close();

            $stmt = $conn->prepare(
                "INSERT INTO coupons (coupon_code, coupon_name, discount_type, discount_value,
                 max_uses, applicable_to, applicable_class, applicable_fee_id,
                 valid_from, valid_until, is_active, created_by)
                 VALUES (?,?,?,?,?,?,?,?,?,?,?,?)"
            );
            $stmt->bind_param('sssdiissssii',
                $coupon_code, $coupon_name, $discount_type, $discount_value,
                $max_uses, $applicable_to, $applicable_class, $applicable_fee_id,
                $valid_from, $valid_until, $is_active, $userId
            );
        } else {
            $stmt = $conn->prepare(
                "UPDATE coupons SET coupon_code=?, coupon_name=?, discount_type=?, discount_value=?,
                 max_uses=?, applicable_to=?, applicable_class=?, applicable_fee_id=?,
                 valid_from=?, valid_until=?, is_active=?
                 WHERE id=?"
            );
            $stmt->bind_param('sssdiisssii',
                $coupon_code, $coupon_name, $discount_type, $discount_value,
                $max_uses, $applicable_to, $applicable_class, $applicable_fee_id,
                $valid_from, $valid_until, $is_active, $id
            );
        }

        if ($stmt->execute()) {
            $new_id = $id === 0 ? (int) $conn->insert_id : $id;
            echo json_encode(['success' => true, 'id' => $new_id, 'message' => 'Coupon saved successfully']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to save coupon: ' . $stmt->error]);
        }
        $stmt->close();
        break;

    // ── DELETE ────────────────────────────────────────────────────────────
    case 'delete':
        if (!in_array($role, ['admin', 'headteacher'], true)) {
            echo json_encode(['success' => false, 'message' => 'Insufficient permissions']); break;
        }
        $id = (int) ($_GET['id'] ?? $_POST['id'] ?? 0);
        if (!$id) { echo json_encode(['success' => false, 'message' => 'Invalid ID']); break; }

        // Check if coupon has been used
        $chk = $conn->prepare("SELECT COUNT(*) AS n FROM coupon_usages WHERE coupon_id = ?");
        $chk->bind_param('i', $id);
        $chk->execute();
        $usage_count = (int) $chk->get_result()->fetch_assoc()['n'];
        $chk->close();

        if ($usage_count > 0) {
            // Deactivate instead of delete
            $stmt = $conn->prepare("UPDATE coupons SET is_active = 0 WHERE id = ?");
            $stmt->bind_param('i', $id);
            $stmt->execute();
            $stmt->close();
            echo json_encode(['success' => true, 'message' => "Coupon has {$usage_count} usage(s) and was deactivated instead of deleted"]);
        } else {
            $stmt = $conn->prepare("DELETE FROM coupons WHERE id = ?");
            $stmt->bind_param('i', $id);
            if ($stmt->execute()) {
                echo json_encode(['success' => true, 'message' => 'Coupon deleted']);
            } else {
                echo json_encode(['success' => false, 'message' => 'Delete failed: ' . $stmt->error]);
            }
            $stmt->close();
        }
        break;

    // ── VALIDATE (key endpoint for payment forms) ─────────────────────────
    case 'validate':
        $coupon_code      = strtoupper(trim((string) ($_POST['coupon_code'] ?? '')));
        $student_id       = (int) ($_POST['student_id'] ?? 0);
        $fee_amount       = floatval($_POST['fee_amount'] ?? 0);
        $class_name       = trim((string) ($_POST['class_name'] ?? ''));
        $fee_structure_id = (int) ($_POST['fee_structure_id'] ?? 0);

        if (empty($coupon_code)) {
            echo json_encode(['valid' => false, 'message' => 'Please enter a coupon code']); break;
        }

        $stmt = $conn->prepare("SELECT * FROM coupons WHERE coupon_code = ? LIMIT 1");
        $stmt->bind_param('s', $coupon_code);
        $stmt->execute();
        $coupon = $stmt->get_result()->fetch_assoc();
        $stmt->close();

        if (!$coupon) {
            echo json_encode(['valid' => false, 'message' => 'Invalid coupon code']); break;
        }
        if (!$coupon['is_active']) {
            echo json_encode(['valid' => false, 'message' => 'This coupon is no longer active']); break;
        }

        $today = date('Y-m-d');
        if ($coupon['valid_from'] && $today < $coupon['valid_from']) {
            echo json_encode(['valid' => false, 'message' => 'This coupon is not yet valid']); break;
        }
        if ($today > $coupon['valid_until']) {
            echo json_encode(['valid' => false, 'message' => 'This coupon has expired']); break;
        }
        if ($coupon['max_uses'] !== null && $coupon['times_used'] >= $coupon['max_uses']) {
            echo json_encode(['valid' => false, 'message' => 'This coupon has reached its maximum usage limit']); break;
        }

        // Applicability check
        if ($coupon['applicable_to'] === 'specific_class' && $coupon['applicable_class'] !== '' && $class_name !== $coupon['applicable_class']) {
            echo json_encode(['valid' => false, 'message' => 'This coupon is only valid for class: ' . htmlspecialchars($coupon['applicable_class'])]); break;
        }
        if ($coupon['applicable_to'] === 'specific_fee' && $coupon['applicable_fee_id'] && $fee_structure_id !== (int) $coupon['applicable_fee_id']) {
            echo json_encode(['valid' => false, 'message' => 'This coupon is not applicable to the selected fee type']); break;
        }

        // Calculate discount
        if ($coupon['discount_type'] === 'percentage') {
            $discount_amount = round($fee_amount * ($coupon['discount_value'] / 100), 2);
        } else {
            $discount_amount = min((float) $coupon['discount_value'], $fee_amount);
        }
        $final_amount = max(0, $fee_amount - $discount_amount);

        $discount_label = $coupon['discount_type'] === 'percentage'
            ? $coupon['discount_value'] . '% discount'
            : 'GHS ' . number_format($coupon['discount_value'], 2) . ' off';

        echo json_encode([
            'valid'          => true,
            'coupon_id'      => (int) $coupon['id'],
            'coupon_name'    => $coupon['coupon_name'],
            'discount_type'  => $coupon['discount_type'],
            'discount_value' => (float) $coupon['discount_value'],
            'discount_amount'=> $discount_amount,
            'final_amount'   => $final_amount,
            'message'        => $discount_label . ' applied — Save GHS ' . number_format($discount_amount, 2),
        ]);
        break;

    // ── RECORD USAGE (called after successful payment) ────────────────────
    case 'record_usage':
        $coupon_id       = (int) ($_POST['coupon_id'] ?? 0);
        $student_id      = (int) ($_POST['student_id'] ?? 0);
        $payment_id      = (int) ($_POST['payment_id'] ?? 0) ?: null;
        $original_amount = floatval($_POST['original_amount'] ?? 0);
        $discount_amount = floatval($_POST['discount_amount'] ?? 0);
        $final_amount    = floatval($_POST['final_amount'] ?? 0);

        if (!$coupon_id || !$student_id) {
            echo json_encode(['success' => false, 'message' => 'Missing required fields']); break;
        }

        $stmt = $conn->prepare(
            "INSERT INTO coupon_usages (coupon_id, student_id, payment_id, original_amount, discount_amount, final_amount)
             VALUES (?,?,?,?,?,?)"
        );
        $stmt->bind_param('iiiddd', $coupon_id, $student_id, $payment_id, $original_amount, $discount_amount, $final_amount);
        if ($stmt->execute()) {
            // Increment times_used
            $upd = $conn->prepare("UPDATE coupons SET times_used = times_used + 1 WHERE id = ?");
            $upd->bind_param('i', $coupon_id);
            $upd->execute();
            $upd->close();
            echo json_encode(['success' => true]);
        } else {
            echo json_encode(['success' => false, 'message' => $stmt->error]);
        }
        $stmt->close();
        break;

    default:
        echo json_encode(['success' => false, 'message' => 'Unknown action']);
}
