<?php
/**
 * Duplicate Entry Check API
 * Returns JSON response indicating if a duplicate entry exists
 */

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

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

$type = $_GET['type'] ?? '';
$vehicleId = $_GET['vehicle_id'] ?? '';
$date = $_GET['date'] ?? '';

if (!$vehicleId || !$date) {
    echo json_encode(['duplicate' => false, 'message' => '']);
    exit;
}

$pdo = getPDO();
$duplicate = false;
$message = '';

if ($type === 'dozar') {
    // Check dozar records for same vehicle on same date
    $stmt = $pdo->prepare("SELECT id, work_location, collector_name FROM dozar_records WHERE vehicle_id = ? AND created_date = ? LIMIT 1");
    $stmt->execute([$vehicleId, $date]);
    $record = $stmt->fetch();
    
    if ($record) {
        $duplicate = true;
        $message = "A dozar record already exists for this vehicle on this date at location: " . $record['work_location'];
    }
} elseif ($type === 'tripper') {
    // Check tripper records - either pending or completed on same date
    $stmt = $pdo->prepare("SELECT id, loading_location, status FROM tripper_records WHERE vehicle_id = ? AND created_date = ? ORDER BY id DESC LIMIT 1");
    $stmt->execute([$vehicleId, $date]);
    $record = $stmt->fetch();
    
    if ($record) {
        $duplicate = true;
        if ($record['status'] === 'pending_unloading') {
            $message = "This vehicle has a pending trip from this date at: " . $record['loading_location'];
        } else {
            $message = "This vehicle has a completed trip from this date at: " . $record['loading_location'];
        }
    }
}

echo json_encode([
    'duplicate' => $duplicate,
    'message' => $message
]);
