<?php
require_once '../config/cors.php';
require_once '../config/database.php';

// --- Database Connection ---
$database = new Database();
$db = $database->getConnection();

$method = $_SERVER['REQUEST_METHOD'];

// --- Handle POST Request (Apply Coupon) ---
if ($method === 'POST') {
    try {
        $db->beginTransaction();

        $data = json_decode(file_get_contents("php://input"), true);
        
        if (!isset($data['code']) || !isset($data['user_id'])) {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Coupon code and User ID are required']);
            exit;
        }

        $couponCode = $data['code'];
        $userId = $data['user_id'];
        
        // SECURITY WARNING: In a production app, get the user ID from a secure session or token, not the request body.

        // --- Step 1: Find and validate the coupon ---
        // FIX: Changed 'is_active' to 'active' and 'usage_count' to 'used_count' to match your database table.
        $stmt = $db->prepare("
            SELECT * FROM coupons 
            WHERE code = :code 
            AND active = 1 
            AND (expires_at IS NULL OR expires_at > NOW())
            AND (usage_limit IS NULL OR used_count < usage_limit)
        ");
        $stmt->bindParam(':code', $couponCode);
        $stmt->execute();
        $coupon = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$coupon) {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Invalid or expired coupon code']);
            $db->rollBack();
            exit;
        }

        // --- Step 2: Check if this user has already used this coupon ---
        // FIX: Changed bindParam for coupon_id from PDO::PARAM_INT to PDO::PARAM_STR because it's a UUID.
        $usageStmt = $db->prepare("SELECT COUNT(*) FROM user_coupon_usage WHERE user_id = :user_id AND coupon_id = :coupon_id");
        $usageStmt->bindParam(':user_id', $userId, PDO::PARAM_STR);
        $usageStmt->bindParam(':coupon_id', $coupon['id'], PDO::PARAM_STR);
        $usageStmt->execute();
        $usageCount = $usageStmt->fetchColumn();

        if ($usageCount > 0) {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'You have already used this coupon']);
            $db->rollBack();
            exit;
        }

        // --- Step 3: Get cart items and calculate subtotal ---
        $cartStmt = $db->prepare("
            SELECT ci.quantity, p.base_price
            FROM cart_items ci
            JOIN products p ON ci.product_id = p.id
            WHERE ci.user_id = :user_id
        ");
        $cartStmt->bindParam(':user_id', $userId, PDO::PARAM_STR);
        $cartStmt->execute();
        $items = $cartStmt->fetchAll(PDO::FETCH_ASSOC);
        
        if (empty($items)) {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Your cart is empty']);
            $db->rollBack();
            exit;
        }

        $subtotal = array_sum(array_map(fn($item) => $item['base_price'] * $item['quantity'], $items));

        // --- Step 4: Calculate the discount amount ---
        // FIX: Changed 'discount_type' to 'type' and 'discount_value' to 'value' to match your database table.
        // FIX: Removed 'max_discount' check as the column doesn't exist in your table.
        $discountAmount = 0;
        if ($coupon['type'] === 'percentage') {
            $discountAmount = ($subtotal * $coupon['value']) / 100;
        } else { // 'fixed' amount
            $discountAmount = min($coupon['value'], $subtotal); // Ensure discount isn't more than the subtotal
        }

        // --- Step 5: Record the coupon usage ---
        // FIX: Changed bindParam for coupon_id from PDO::PARAM_INT to PDO::PARAM_STR.
        $recordUsageStmt = $db->prepare("INSERT INTO user_coupon_usage (user_id, coupon_id) VALUES (:user_id, :coupon_id)");
        $recordUsageStmt->bindParam(':user_id', $userId, PDO::PARAM_STR);
        $recordUsageStmt->bindParam(':coupon_id', $coupon['id'], PDO::PARAM_STR);
        $recordUsageStmt->execute();

        // FIX: Changed 'usage_count' to 'used_count'. Changed bindParam to PDO::PARAM_STR.
        $updateCountStmt = $db->prepare("UPDATE coupons SET used_count = used_count + 1 WHERE id = :coupon_id");
        $updateCountStmt->bindParam(':coupon_id', $coupon['id'], PDO::PARAM_STR);
        $updateCountStmt->execute();
        
        $db->commit();

        $total = $subtotal - $discountAmount;

        http_response_code(200);
        echo json_encode([
            'success' => true,
            'message' => 'Coupon applied successfully',
            'coupon' => [
                'code' => $coupon['code'],
                'discount_amount' => round($discountAmount, 2),
            ],
            'subtotal' => round($subtotal, 2),
            'total' => round($total, 2)
        ]);

    } catch (Exception $e) {
        if ($db->inTransaction()) {
            $db->rollBack();
        }
        http_response_code(500);
        echo json_encode([
            'success' => false,
            'message' => 'Internal Server Error: ' . $e->getMessage()
        ]);
    }

// --- Handle DELETE Request (Remove Coupon) ---
} elseif ($method === 'DELETE') {
    try {
        if (!isset($_GET['user_id'])) {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'User ID is required']);
            exit;
        }
        
        $userId = $_GET['user_id'];

        // Start transaction
        $db->beginTransaction();

        // Get the coupon ID before deleting the usage record
        $getCouponStmt = $db->prepare("SELECT coupon_id FROM user_coupon_usage WHERE user_id = :user_id");
        $getCouponStmt->bindParam(':user_id', $userId, PDO::PARAM_STR);
        $getCouponStmt->execute();
        $couponId = $getCouponStmt->fetchColumn();

        if ($couponId) {
            // Decrease the used_count in coupons table
            $updateCountStmt = $db->prepare("UPDATE coupons SET used_count = used_count - 1 WHERE id = :coupon_id");
            $updateCountStmt->bindParam(':coupon_id', $couponId, PDO::PARAM_STR);
            $updateCountStmt->execute();

            // Delete the coupon usage record
            $deleteUsageStmt = $db->prepare("DELETE FROM user_coupon_usage WHERE user_id = :user_id");
            $deleteUsageStmt->bindParam(':user_id', $userId, PDO::PARAM_STR);
            $deleteUsageStmt->execute();
        }

        $db->commit();

        $stmt = $db->prepare("
            SELECT ci.*, p.name, p.base_price, p.brand, pi.url as image_url
            FROM cart_items ci
            JOIN products p ON ci.product_id = p.id
            LEFT JOIN product_images pi ON p.id = pi.product_id AND pi.position = 0
            WHERE ci.user_id = :user_id
        ");
        $stmt->bindParam(':user_id', $userId, PDO::PARAM_STR);
        $stmt->execute();
        $items = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $total = array_sum(array_map(fn($item) => $item['base_price'] * $item['quantity'], $items));

        http_response_code(200);
        echo json_encode([
            'success' => true,
            'message' => 'Coupon removed successfully',
            'items' => $items,
            'total' => round($total, 2)
        ]);

    } catch (Exception $e) {
        if ($db->inTransaction()) {
            $db->rollBack();
        }
        http_response_code(500);
        echo json_encode([
            'success' => false,
            'message' => 'Internal Server Error: ' . $e->getMessage()
        ]);
    }

// --- Handle Other Methods ---
} else {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
}
?>
