<?php
// backend/api/rides.php

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

require_once '../config/db.php';

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

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

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

$platformInput = $input['platform'] ?? 'Unknown';

// Map package names to ENUM values
$platformMap = [
    'com.ubercab.driver' => 'Uber',
    'com.careem.adma' => 'Careem',
    'me.com.easytaxista' => 'Jeeny',
    'com.PetraRide_Captain' => 'Petra Ride',
    'com.taxif.driver' => 'TaxiF'
];

$platform = $platformMap[$platformInput] ?? ($platformInput ?: 'Unknown');

// Ensure the platform matches one of the ENUM values
$allowedPlatforms = ['Uber', 'Careem', 'Jeeny', 'Petra Ride', 'TaxiF', 'Unknown'];
if (!in_array($platform, $allowedPlatforms)) {
    $platform = 'Unknown';
}

$price = $input['price'] ?? 0.0;
$pickupDistance = $input['pickupDistance'] ?? 'Unknown';
$dropoffDistance = $input['dropoffDistance'] ?? 'Unknown';
$timeToPickup = $input['timeToPickup'] ?? 'Unknown';
$pickupAddress = $input['pickupAddress'] ?? 'Unknown';
$dropoffAddress = $input['dropoffAddress'] ?? 'Unknown';
$isAccepted = isset($input['isAccepted']) ? (int)$input['isAccepted'] : 0;
$rawText = $input['rawText'] ?? '';
$fingerprint = $input['fingerprint'] ?? 'UNKNOWN_DEVICE';
$latitude = $input['latitude'] ?? null;
$longitude = $input['longitude'] ?? null;

try {
    // --- Subscription Quota Check ---
    if ($isAccepted === 1) {
        $today = date('Y-m-d');
        
        // Get active subscription
        $stmt = $pdo->prepare("SELECT plan, expires_at FROM subscriptions WHERE fingerprint = :fingerprint AND is_active = 1 ORDER BY id DESC LIMIT 1");
        $stmt->execute([':fingerprint' => $fingerprint]);
        $sub = $stmt->fetch(PDO::FETCH_ASSOC);
        
        $plan = 'free';
        if ($sub) {
            $plan = $sub['plan'];
            if ($sub['expires_at'] && strtotime($sub['expires_at']) < time()) {
                $plan = 'free'; // Expired
            }
        }

        // Get daily usage
        $stmt = $pdo->prepare("SELECT rides_accepted FROM daily_usage WHERE fingerprint = :fingerprint AND usage_date = :today");
        $stmt->execute([':fingerprint' => $fingerprint, ':today' => $today]);
        $usage = $stmt->fetch(PDO::FETCH_ASSOC);
        $ridesToday = $usage ? (int)$usage['rides_accepted'] : 0;

        // Determine limit
        $limit = 1; // free
        if ($plan === 'basic') $limit = 10;
        if ($plan === 'pro' || $plan === 'annual') $limit = -1;

        if ($limit !== -1 && $ridesToday >= $limit) {
            http_response_code(403);
            echo json_encode([
                'success' => false, 
                'message' => 'Daily limit reached',
                'plan' => $plan,
                'upgrade_required' => true
            ]);
            exit;
        }
        
        // Update daily usage
        $stmt = $pdo->prepare("INSERT INTO daily_usage (fingerprint, usage_date, rides_accepted) VALUES (:fingerprint, :today, 1) ON DUPLICATE KEY UPDATE rides_accepted = rides_accepted + 1");
        $stmt->execute([':fingerprint' => $fingerprint, ':today' => $today]);
    }
    // --------------------------------

    $sql = "INSERT INTO rides (fingerprint, platform, price, pickup_distance, dropoff_distance, time_to_pickup, pickup_address, dropoff_address, is_accepted, raw_text, latitude, longitude, created_at) 
            VALUES (:fingerprint, :platform, :price, :pickup_distance, :dropoff_distance, :time_to_pickup, :pickup_address, :dropoff_address, :is_accepted, :raw_text, :latitude, :longitude, NOW())";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute([
        ':fingerprint' => $fingerprint,
        ':platform' => $platform,
        ':price' => $price,
        ':pickup_distance' => $pickupDistance,
        ':dropoff_distance' => $dropoffDistance,
        ':time_to_pickup' => $timeToPickup,
        ':pickup_address' => $pickupAddress,
        ':dropoff_address' => $dropoffAddress,
        ':is_accepted' => $isAccepted,
        ':raw_text' => $rawText,
        ':latitude' => $latitude,
        ':longitude' => $longitude
    ]);

    http_response_code(201);
    echo json_encode([
        'success' => true,
        'message' => 'Ride record created successfully',
        'ride_id' => $pdo->lastInsertId()
    ]);
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
?>
