<?php
/**
 * Add Tripper Loading Entry Page
 * Dozar & Tripper Management System
 */

require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/nepali_calendar.php';

$user = getCurrentUser();
$pdo = getPDO();
$error = '';
$success = '';
$duplicateWarning = '';

// Get user's assigned projects
$projectFilter = '';
$params = [];
if ($user['role'] !== 'admin' && $user['role'] !== 'viewer' && $user['assigned_projects']) {
    $projectIds = explode(',', $user['assigned_projects']);
    $placeholders = implode(',', array_fill(0, count($projectIds), '?'));
    $projectFilter = "WHERE id IN ($placeholders)";
    $params = $projectIds;
}

// Get dropdown data
$projects = [];
$stmt = $pdo->query("SELECT * FROM projects WHERE is_active = 1 ORDER BY project_name");
while ($row = $stmt->fetch()) {
    $projects[$row['id']] = $row['project_name'];
}

$vehicles = [];
$vehicleFilter = "";
if ($user['role'] === 'collector' && ($user['collector_access'] === 'tripper_loading_only' || $user['collector_access'] === 'tripper_unloading_only')) {
    $vehicleFilter = " AND vehicle_type = 'Tripper'";
}
$stmt = $pdo->query("SELECT * FROM vehicles WHERE is_active = 1" . $vehicleFilter . " ORDER BY vehicle_number");
while ($row = $stmt->fetch()) {
    $vehicles[] = [
        'id'          => $row['id'],
        'label'       => $row['vehicle_number'] . ' (' . $row['vehicle_type'] . ')',
        'entity_type' => $row['entity_type'] ?? 'kmc',
    ];
}

$drivers = [];
$stmt = $pdo->query("SELECT * FROM drivers WHERE is_active = 1 ORDER BY full_name");
while ($row = $stmt->fetch()) {
    $drivers[$row['id']] = $row['full_name'];
}

$deployed = [];
$stmt = $pdo->query("SELECT * FROM deployed_from WHERE is_active = 1 ORDER BY entity_name");
while ($row = $stmt->fetch()) {
    $deployed[] = [
        'id'          => $row['id'],
        'name'        => $row['entity_name'],
        'entity_type' => $row['entity_type'] ?? 'other',
    ];
}

$groups = [];
$stmt = $pdo->query("SELECT * FROM groups WHERE is_active = 1 ORDER BY group_name");
while ($row = $stmt->fetch()) {
    $groups[$row['id']] = $row['group_name'];
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $entity_type_select = sanitize($_POST['entity_type_select'] ?? '');
    $project_id = sanitize($_POST['project_id'] ?? '');
    $deployed_from_id = sanitize($_POST['deployed_from_id'] ?? '');
    $vehicle_id = sanitize($_POST['vehicle_id'] ?? '');
    $driver_id = sanitize($_POST['driver_id'] ?? '');
    $created_date = sanitize($_POST['created_date'] ?? date('Y-m-d'));
    $work_location = sanitize($_POST['work_location'] ?? '');
    $group_id = sanitize($_POST['group_id'] ?? '');
    $material_type = sanitize($_POST['material_type'] ?? '');
    $quantity_weight = sanitize($_POST['quantity_weight'] ?? '');
    $loading_location = sanitize($_POST['loading_location'] ?? '');
    $loading_start_odometer = sanitize($_POST['loading_start_odometer'] ?? '');
    $loading_time = sanitize($_POST['loading_time'] ?? date('H:i'));
    $loading_collector_address = sanitize($_POST['loading_collector_address'] ?? '');
    $loading_remarks = sanitize($_POST['loading_remarks'] ?? '');
    $gps_latitude = sanitize($_POST['gps_latitude'] ?? '');
    $gps_longitude = sanitize($_POST['gps_longitude'] ?? '');
    $gps_address = sanitize($_POST['gps_address'] ?? '');
    
    // Check for pending trip (same vehicle with pending unloading)
    $stmt = $pdo->prepare("SELECT id, created_date, loading_location, status FROM tripper_records WHERE vehicle_id = ? AND status = 'pending_unloading' LIMIT 1");
    $stmt->execute([$vehicle_id]);
    $duplicate = $stmt->fetch();
    if ($duplicate) {
        $error = 'Error: No new trip allowed. This vehicle has a pending trip (loaded at ' . $duplicate['loading_location'] . ' on ' . $duplicate['created_date'] . ') that must be UNLOADED first.';
    }
    
    // Validate
    if (!$project_id || !$deployed_from_id || !$vehicle_id || !$driver_id || !$loading_location) {
        $error = 'Please fill in all required fields';
    } elseif ($project_id === 'new' && (empty($_POST['new_project_name']) || empty($_POST['new_project_code']))) {
        $error = 'Please provide a new project name and code';
    } elseif ($deployed_from_id === 'new' && empty($_POST['new_deployed'])) {
        $error = 'Please provide a new deployed from entity name';
    } elseif ($vehicle_id === 'new' && empty($_POST['new_vehicle_number'])) {
        $error = 'Please provide a new vehicle number';
    } elseif ($driver_id === 'new' && empty($_POST['new_driver_name'])) {
        $error = 'Please provide a new driver name';
    } elseif ($group_id === 'new' && empty($_POST['new_group_name'])) {
        $error = 'Please provide a new group name';
    } else {
        // Handle new project FIRST
        if ($project_id === 'new' && !empty($_POST['new_project_name']) && !empty($_POST['new_project_code'])) {
            $stmt = $pdo->prepare("SELECT id FROM projects WHERE project_code = ?");
            $stmt->execute([sanitize($_POST['new_project_code'])]);
            if ($stmt->fetch()) {
                $error = 'A project with this code already exists.';
            } else {
                $stmt = $pdo->prepare("INSERT INTO projects (project_name, project_code, description) VALUES (?, ?, ?)");
                $stmt->execute([sanitize($_POST['new_project_name']), sanitize($_POST['new_project_code']), sanitize($_POST['new_project_description'] ?? '')]);
                $project_id = $pdo->lastInsertId();
            }
        }
        
        if (empty($error)) {
        
        // Handle new vehicle
        if ($vehicle_id === 'new' && !empty($_POST['new_vehicle_number'])) {
            $stmt = $pdo->prepare("SELECT id FROM vehicles WHERE vehicle_number = ?");
            $stmt->execute([sanitize($_POST['new_vehicle_number'])]);
            if (!$stmt->fetch()) {
                $vt = sanitize($_POST['new_vehicle_type'] ?? 'Tripper');
                if ($vt === 'other') $vt = sanitize($_POST['new_vehicle_type_custom'] ?? 'Tripper');
                $newVehicleEntity = in_array($entity_type_select ?? '', ['kmc','private','other']) ? $entity_type_select : 'kmc';
                $stmt = $pdo->prepare("INSERT INTO vehicles (vehicle_number, vehicle_type, entity_type) VALUES (?, ?, ?)");
                $stmt->execute([sanitize($_POST['new_vehicle_number']), $vt, $newVehicleEntity]);
                $vehicle_id = $pdo->lastInsertId();
            } else {
                $error = 'Vehicle already exists';
            }
        }
        
        if ($driver_id === 'new' && !empty($_POST['new_driver_name']) && empty($error)) {
            $stmt = $pdo->prepare("SELECT id FROM drivers WHERE full_name = ? AND phone_number = ?");
            $stmt->execute([sanitize($_POST['new_driver_name']), sanitize($_POST['new_driver_phone'] ?? '')]);
            if (!$stmt->fetch()) {
                $stmt = $pdo->prepare("INSERT INTO drivers (full_name, phone_number, address) VALUES (?, ?, ?)");
                $stmt->execute([sanitize($_POST['new_driver_name']), sanitize($_POST['new_driver_phone'] ?? ''), sanitize($_POST['new_driver_address'] ?? '')]);
                $driver_id = $pdo->lastInsertId();
            } else {
                $error = 'Driver already exists';
            }
        }
        
        if ($deployed_from_id === 'new' && !empty($_POST['new_deployed']) && empty($error)) {
            $stmt = $pdo->prepare("SELECT id FROM deployed_from WHERE entity_name = ?");
            $stmt->execute([sanitize($_POST['new_deployed'])]);
            if (!$stmt->fetch()) {
                $newDeployedEntity = in_array($entity_type_select ?? '', ['kmc','private','other']) ? $entity_type_select : 'other';
                $stmt = $pdo->prepare("INSERT INTO deployed_from (entity_name, entity_type) VALUES (?, ?)");
                $stmt->execute([sanitize($_POST['new_deployed']), $newDeployedEntity]);
                $deployed_from_id = $pdo->lastInsertId();
            } else {
                $error = 'Entity already exists';
            }
        }
        
        if ($group_id === 'new' && !empty($_POST['new_group_name']) && empty($error)) {
            $stmt = $pdo->prepare("SELECT id FROM groups WHERE group_name = ?");
            $stmt->execute([sanitize($_POST['new_group_name'])]);
            if (!$stmt->fetch()) {
                $stmt = $pdo->prepare("INSERT INTO groups (group_name, description) VALUES (?, ?)");
                $stmt->execute([sanitize($_POST['new_group_name']), sanitize($_POST['new_group_description'] ?? '')]);
                $group_id = $pdo->lastInsertId();
            } else {
                $error = 'Group already exists';
            }
        }
        
        if (empty($error)) {
        
        // Handle photo upload
        $photo_path = '';
        if (isset($_FILES['photo']) && $_FILES['photo']['error'] === UPLOAD_ERR_OK) {
            $uploadDir = __DIR__ . '/../uploads/tripper/';
            if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);
            $fileExt = pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION);
            $fileName = 'tripper_' . time() . '.' . $fileExt;
            $targetPath = $uploadDir . $fileName;
            if (move_uploaded_file($_FILES['photo']['tmp_name'], $targetPath)) {
                $photo_path = 'uploads/tripper/' . $fileName;
            }
        }
        
        $sql = "INSERT INTO tripper_records 
                (project_id, deployed_from_id, vehicle_id, driver_id, created_date, work_location, 
                 group_id, material_type, quantity_weight, 
                 loading_collector_id, loading_location, loading_collector_address, 
                 loading_gps_latitude, loading_gps_longitude, loading_gps_address, loading_gps_captured_at,
                 loading_start_odometer, loading_time, loading_photo_path, loading_remarks, status) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending_unloading')";
        
        $stmt = $pdo->prepare($sql);
        try {
            $stmt->execute([
                $project_id, $deployed_from_id, $vehicle_id, $driver_id, $created_date, $work_location,
                $group_id ?: null, $material_type, $quantity_weight,
                $user['id'], $loading_location, $loading_collector_address,
                $gps_latitude, $gps_longitude, $gps_address, $gps_latitude ? date('Y-m-d H:i:s') : null,
                $loading_start_odometer, $loading_time, $photo_path, $loading_remarks
            ]);
            $newTripId = $pdo->lastInsertId();
            showMessage('Loading entry added successfully! Pending for unloading.', 'success');
            redirect('add_loading.php');

            // Log activity
            if (file_exists(__DIR__ . '/../includes/activity_log.php')) {
                require_once __DIR__ . '/../includes/activity_log.php';
                logActivity($pdo, 'create', 'tripper', $newTripId, "Loading entry: Vehicle $vehicle_id at $loading_location");
            }
        } catch (Exception $e) {
            $error = 'Error: ' . $e->getMessage();
        }
        }
        }
    }
}

$pageTitle = "Add Loading Entry";
?>
<?php include __DIR__ . '/../includes/header.php'; ?>

<?php displayMessage(); ?>

<div class="row">
    <div class="col-12">
        <h2><i class="fas fa-truck-loading"></i> <?php echo t('action_loading_entry', 'Add Loading Entry'); ?></h2>
    </div>
</div>

<?php if ($error): ?>
<div class="alert alert-danger"><?php echo $error; ?></div>
<?php endif; ?>

<?php if ($duplicateWarning && !$success): ?>
<div class="alert alert-warning">
    <i class="fas fa-exclamation-triangle"></i> <?php echo $duplicateWarning; ?>
</div>
<?php endif; ?>

<?php if ($success): ?>
<div class="alert alert-success"><?php echo $success; ?>
    <a href="index.php" class="btn btn-sm btn-success ms-2"><?php echo t('action_view', 'View Records'); ?></a>
    <a href="add_loading.php" class="btn btn-sm btn-primary"><?php echo t('action_add_new', 'Add Another'); ?></a>
</div>
<?php endif; ?>

<style>
.entity-btn { min-width:120px; font-weight:700; font-size:1rem; border-radius:12px; padding:.7rem 1.4rem; transition:all .2s; }
.entity-btn.active-kmc     { background:#0d6efd; color:#fff; border-color:#0d6efd; }
.entity-btn.active-private { background:#6f42c1; color:#fff; border-color:#6f42c1; }
.entity-btn.active-other   { background:#20c997; color:#fff; border-color:#20c997; }
</style>

<form method="POST" action="" enctype="multipart/form-data" class="row g-3" onsubmit="return validateForm()">

    <!-- STEP 1: Entity Type -->
    <div class="col-12">
        <div class="card border-0 shadow-sm mb-2" style="border-radius:14px;background:#f8faff;">
            <div class="card-body py-3 px-4">
                <label class="form-label fw-bold mb-2" style="font-size:1.05rem;">
                    <i class="fas fa-layer-group me-2 text-primary"></i> Step 1 — Select Entity Type *
                </label>
                <div class="d-flex gap-3 flex-wrap">
                    <button type="button" class="btn btn-outline-primary entity-btn" id="btn-kmc"
                            onclick="selectEntityType('kmc')">
                        <i class="fas fa-city me-1"></i> KMC
                    </button>
                    <button type="button" class="btn btn-outline-secondary entity-btn" id="btn-private"
                            onclick="selectEntityType('private')">
                        <i class="fas fa-building me-1"></i> Private
                    </button>
                    <button type="button" class="btn btn-outline-success entity-btn" id="btn-other"
                            onclick="selectEntityType('other')">
                        <i class="fas fa-layer-group me-1"></i> Other
                    </button>
                </div>
                <input type="hidden" name="entity_type_select" id="entity_type_select">
            </div>
        </div>
    </div>

    <!-- Project Selection -->
    <div class="col-md-4">
        <label class="form-label"><?php echo t('label_project', 'Project'); ?> *</label>
        <select name="project_id" id="project_id" class="form-select" required onchange="handleProjectChange()">
            <option value=""><?php echo t('option_select_project', 'Select Project'); ?></option>
            <?php foreach ($projects as $id => $name): ?>
            <option value="<?php echo $id; ?>"><?php echo $name; ?></option>
            <?php endforeach; ?>
            <option value="new"><?php echo t('option_add_new', '+ Add New Project'); ?></option>
        </select>
    </div>
    
    <!-- New Project Fields (Hidden) -->
    <div class="col-md-4 new-project-field" id="new_project_fields" style="display:none;">
        <label class="form-label"><?php echo t('label_project_name', 'Project Name'); ?> (New)</label>
        <input type="text" name="new_project_name" class="form-control" placeholder="<?php echo t('label_project_name', 'Enter project name'); ?>">
    </div>
    <div class="col-md-4 new-project-field" id="new_project_code" style="display:none;">
        <label class="form-label"><?php echo t('label_project_code', 'Project Code'); ?> (New)</label>
        <input type="text" name="new_project_code" class="form-control" placeholder="<?php echo t('label_project_code', 'Enter project code'); ?>">
    </div>
    
    <!-- Deployed From -->
    <div class="col-md-4">
        <label class="form-label"><?php echo t('label_deployed_from', 'Deployed From'); ?> *</label>
        <select name="deployed_from_id" id="deployed_from_id" class="form-select" required>
            <option value=""><?php echo t('option_select', 'Select'); ?></option>
            <?php foreach ($deployed as $d): ?>
            <option value="<?php echo $d['id']; ?>" data-entity="<?php echo $d['entity_type']; ?>" style="display:none"><?php echo $d['name']; ?></option>
            <?php endforeach; ?>
            <option value="new" style="display:none"><?php echo t('option_add_new', '+ Add New'); ?></option>
        </select>
    </div>
    
    <!-- New Deployed (Hidden by default) -->
    <div class="col-md-4 new-field" id="new_deployed_field" style="display:none;">
        <label class="form-label"><?php echo t('label_deployed_from', 'Deployed From'); ?> (New)</label>
        <input type="text" name="new_deployed" class="form-control" placeholder="<?php echo t('label_deployed_from', 'Enter name'); ?>">
    </div>
    
    <!-- Vehicle Selection -->
    <div class="col-md-4">
        <label class="form-label"><?php echo t('label_vehicle', 'Vehicle'); ?> *</label>
        <select name="vehicle_id" id="vehicle_id" class="form-select" required onchange="handleVehicleChange(); checkPendingTrip();">
            <option value=""><?php echo t('option_select_vehicle', 'Select Vehicle'); ?></option>
            <?php foreach ($vehicles as $v): ?>
            <option value="<?php echo $v['id']; ?>" data-entity="<?php echo $v['entity_type']; ?>" style="display:none"><?php echo $v['label']; ?></option>
            <?php endforeach; ?>
            <option value="new" style="display:none"><?php echo t('option_add_new', '+ Add New Vehicle'); ?></option>
        </select>
    </div>
    
    <!-- New Vehicle Fields (Hidden) -->
    <div class="col-md-4 new-vehicle-field" id="new_vehicle_fields" style="display:none;">
        <label class="form-label"><?php echo t('label_vehicle_number', 'Vehicle Number'); ?></label>
        <input type="text" name="new_vehicle_number" class="form-control" placeholder="e.g., Ba 1 Ja 2977">
    </div>
    <div class="col-md-4 new-vehicle-field" id="new_vehicle_type_field" style="display:none;">
        <label class="form-label"><?php echo t('label_vehicle_type', 'Vehicle Type'); ?></label>
        <select name="new_vehicle_type" class="form-select" id="new_vehicle_type_select" onchange="handleVehicleTypeChange()">
            <option value="Tripper"><?php echo t('vehicle_type_tripper', 'Tripper'); ?></option>
            <option value="Dozar"><?php echo t('vehicle_type_dozer', 'Dozar'); ?></option>
            <option value="JCB"><?php echo t('vehicle_type_jcb', 'JCB'); ?></option>
            <option value="Excavator"><?php echo t('vehicle_type_excavator', 'Excavator'); ?></option>
            <option value="Tipper"><?php echo t('vehicle_type_tipper', 'Tipper'); ?></option>
            <option value="Dumper"><?php echo t('vehicle_type_dumper', 'Dumper'); ?></option>
            <option value="Loader"><?php echo t('vehicle_type_loader', 'Loader'); ?></option>
            <option value="other"><?php echo t('vehicle_type_other', 'Other (Specify)'); ?></option>
        </select>
        <input type="text" name="new_vehicle_type_custom" id="new_vehicle_type_custom" class="form-control mt-2" placeholder="Enter vehicle type" style="display:none;">
    </div>
    
    <!-- Driver Selection -->
    <div class="col-md-4">
        <label class="form-label"><?php echo t('label_driver', 'Driver'); ?> *</label>
        <select name="driver_id" id="driver_id" class="form-select" required onchange="handleDriverChange()">
            <option value=""><?php echo t('option_select_driver', 'Select Driver'); ?></option>
            <?php foreach ($drivers as $id => $name): ?>
            <option value="<?php echo $id; ?>"><?php echo $name; ?></option>
            <?php endforeach; ?>
            <option value="new"><?php echo t('option_add_new', '+ Add New Driver'); ?></option>
        </select>
    </div>
    
    <!-- New Driver Fields (Hidden) -->
    <div class="col-md-4 new-driver-field" id="new_driver_fields" style="display:none;">
        <label class="form-label"><?php echo t('label_driver_name', 'Driver Name'); ?></label>
        <input type="text" name="new_driver_name" class="form-control" placeholder="<?php echo t('label_driver_name', 'Full Name'); ?>">
    </div>
    <div class="col-md-4 new-driver-field" id="new_driver_phone" style="display:none;">
        <label class="form-label"><?php echo t('label_phone', 'Phone Number'); ?></label>
        <input type="tel" name="new_driver_phone" inputmode="tel" class="form-control" placeholder="98XXXXXXXX">
    </div>
    <div class="col-md-4 new-driver-field" id="new_driver_address" style="display:none;">
        <label class="form-label"><?php echo t('label_address', 'Address'); ?></label>
        <input type="text" name="new_driver_address" class="form-control" placeholder="<?php echo t('label_address', 'Address'); ?>">
    </div>
    
    <!-- Date -->
    <div class="col-md-4">
        <label class="form-label">Date (नेपाली) *</label>
        <?php echo nepali_date_picker('created_date', get_nepali_date_input_value(), 'created_date', 'form-control', true); ?>
    </div>
    
    <div class="col-md-4">
        <label class="form-label">Group</label>
        <select name="group_id" id="group_id" class="form-select" onchange="handleGroupChange()">
            <option value="">Select Group</option>
            <?php foreach ($groups as $id => $name): ?>
            <option value="<?php echo $id; ?>"><?php echo $name; ?></option>
            <?php endforeach; ?>
            <option value="new"><?php echo t('option_add_new', '+ Add New Group'); ?></option>
        </select>
    </div>
    
    <!-- New Group Fields (Hidden) -->
    <div class="col-md-4 new-group-field" id="new_group_fields" style="display:none;">
        <label class="form-label"><?php echo t('label_group_name', 'Group Name'); ?> (New)</label>
        <input type="text" name="new_group_name" class="form-control" placeholder="<?php echo t('label_group_name', 'Enter group name'); ?>">
    </div>
    
    <!-- Work Location -->
    <div class="col-md-6">
        <label class="form-label"><?php echo t('label_work_location', 'Work Location'); ?> *</label>
        <input type="text" name="work_location" class="form-control" placeholder="<?php echo t('label_work_location', 'Enter work location'); ?>" required>
    </div>
    
    <!-- Material -->
    <div class="col-md-6">
        <label class="form-label">Material Type</label>
        <input type="text" name="material_type" class="form-control" placeholder="e.g., Garbage, Waste">
    </div>
    
    <div class="col-md-6">
        <label class="form-label">Quantity/Weight</label>
        <input type="text" inputmode="decimal" name="quantity_weight" class="form-control" placeholder="e.g., 5 Ton">
    </div>
    
    <!-- Loading Info -->
    <div class="col-12">
        <h5 class="border-bottom pb-2">Loading Information</h5>
    </div>
    
    <div class="col-md-6">
        <label class="form-label"><?php echo t('label_loading_location', 'Loading Location'); ?> *</label>
        <input type="text" name="loading_location" class="form-control" placeholder="<?php echo t('label_loading_location', 'Enter loading location'); ?>" required>
    </div>
    
    <div class="col-md-3">
        <label class="form-label">Start Odometer (KM) *</label>
        <input type="number" step="0.01" inputmode="decimal" name="loading_start_odometer" id="loading_start_odometer" class="form-control" required>
    </div>
    
    <div class="col-md-3">
        <label class="form-label">Loading Time</label>
        <input type="time" name="loading_time" class="form-control" value="<?php echo date('H:i'); ?>">
    </div>
    
    <!-- GPS Location -->
    <div class="col-md-6">
        <label class="form-label">GPS Location</label>
        <button type="button" class="btn btn-outline-secondary" onclick="captureGPS('gps_latitude', 'gps_longitude', 'gps_address')">
            <i class="fas fa-map-marker-alt"></i> Capture GPS
        </button>
        <input type="hidden" name="gps_latitude" id="gps_latitude">
        <input type="hidden" name="gps_longitude" id="gps_longitude">
    </div>
    
    <div class="col-md-6">
        <label class="form-label">GPS Address (Auto-filled)</label>
        <input type="text" name="gps_address" id="gps_address" class="form-control" readonly placeholder="Address from GPS" <?php echo hasRole('admin') ? '' : 'style="display:none;"'; ?>>
    </div>
    
    <!-- Collector Self-Declared Address -->
    <div class="col-md-6">
        <label class="form-label"><?php echo t('label_address', 'Your Location'); ?> (Self-Declared)</label>
        <input type="text" name="loading_collector_address" class="form-control" placeholder="<?php echo t('label_address', 'Enter your current location'); ?>">
    </div>
    
    <!-- Photo -->
    <div class="col-md-6">
        <label class="form-label">Photo</label>
        <input type="file" name="photo" class="form-control" accept="image/*">
    </div>
    
    <!-- Remarks -->
    <div class="col-12">
        <label class="form-label">Remarks</label>
        <textarea name="loading_remarks" class="form-control" rows="3" placeholder="Any additional notes..."></textarea>
    </div>
    
    <!-- Submit Buttons -->
    <div class="col-12">
        <button type="submit" class="btn btn-primary">
            <i class="fas fa-save"></i> Save Loading Entry
        </button>
        <a href="index.php" class="btn btn-secondary">
            <i class="fas fa-times"></i> Cancel
        </a>
    </div>
</form>

<script>
// Global state to track pending trip status
let isTripPending = false;
let selectedEntityType = '';

function selectEntityType(type) {
    selectedEntityType = type;
    document.getElementById('entity_type_select').value = type;

    // Update button styles
    ['kmc','private','other'].forEach(t => {
        const btn = document.getElementById('btn-' + t);
        btn.className = 'btn entity-btn ' + (t === type ? 'active-' + t : 'btn-outline-secondary');
    });

    // Filter deployed_from options
    const depSelect = document.getElementById('deployed_from_id');
    depSelect.value = '';
    depSelect.querySelectorAll('option').forEach(opt => {
        if (!opt.value) { opt.style.display = ''; return; }
        opt.style.display = (opt.value === 'new' || opt.dataset.entity === type) ? '' : 'none';
    });
    // Auto-select if only one match
    const depMatches = [...depSelect.querySelectorAll('option')].filter(o => o.dataset.entity === type);
    if (depMatches.length === 1) depSelect.value = depMatches[0].value;

    // Filter vehicle options
    const vehSelect = document.getElementById('vehicle_id');
    vehSelect.value = '';
    vehSelect.querySelectorAll('option').forEach(opt => {
        if (!opt.value) { opt.style.display = ''; return; }
        opt.style.display = (opt.value === 'new' || opt.dataset.entity === type) ? '' : 'none';
    });
}

// Enhanced Form validation
function validateForm() {
    if (!selectedEntityType) {
        alert('Please select Entity Type first (KMC / Private / Other)');
        document.getElementById('btn-kmc').focus();
        return false;
    }
    if (isTripPending) {
        alert('Blocked: You cannot add a new load for this vehicle until the previous trip is marked as completed (Unloaded).');
        document.getElementById('vehicle_id').focus();
        return false;
    }
    const projectId = document.getElementById('project_id').value;
    const vehicleId = document.getElementById('vehicle_id').value;
    const driverId = document.getElementById('driver_id').value;
    const deployedFromId = document.getElementById('deployed_from_id').value;
    const loadingLocation = document.getElementById('loading_location').value.trim();
    const loadingStartOdometer = parseFloat(document.getElementById('loading_start_odometer').value) || 0;
    const createdDate = document.getElementById('created_date').value;
    
    // Check required fields
    if (!projectId) {
        alert('Please select a project');
        document.getElementById('project_id').focus();
        return false;
    }
    
    if (!deployedFromId) {
        alert('Please select deployed from');
        document.getElementById('deployed_from_id').focus();
        return false;
    }
    
    if (!vehicleId) {
        alert('Please select a vehicle');
        document.getElementById('vehicle_id').focus();
        return false;
    }
    
    if (!driverId) {
        alert('Please select a driver');
        document.getElementById('driver_id').focus();
        return false;
    }
    
    if (!createdDate) {
        alert('Please select a date');
        document.getElementById('created_date').focus();
        return false;
    }
    
    // Check for future date
    const today = new Date().toISOString().split('T')[0];
    if (createdDate > today) {
        alert('Date cannot be in the future');
        document.getElementById('created_date').focus();
        return false;
    }
    
    if (!loadingLocation) {
        alert('Please enter loading location');
        document.getElementById('loading_location').focus();
        return false;
    }
    
    if (loadingStartOdometer <= 0) {
        alert('Please enter a valid starting odometer reading');
        document.getElementById('loading_start_odometer').focus();
        return false;
    }
    
    // Validate new vehicle fields if adding new vehicle
    if (vehicleId === 'new') {
        const newVehicleNumber = document.querySelector('input[name="new_vehicle_number"]').value.trim();
        if (!newVehicleNumber) {
            alert('Please enter new vehicle number');
            return false;
        }
    }
    
    // Validate new driver fields if adding new driver
    if (driverId === 'new') {
        const newDriverName = document.querySelector('input[name="new_driver_name"]').value.trim();
        if (!newDriverName) {
            alert('Please enter driver name');
            return false;
        }
    }
    
    // Disable submit button to prevent double submission
    const submitBtn = document.querySelector('button[type="submit"]');
    if (submitBtn) {
        submitBtn.disabled = true;
        submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i> Saving...';
    }
    
    return true;
}

// Real-time duplicate check for pending trips
function checkPendingTrip() {
    const vehicleId = document.getElementById('vehicle_id').value;
    
    if (vehicleId && vehicleId !== 'new') {
        fetch('../get_duplicate_check.php?type=tripper&vehicle_id=' + vehicleId + '&date=' + new Date().toISOString().split('T')[0])
            .then(response => response.json())
            .then(data => {
                if (data.duplicate) {
                    let warningEl = document.getElementById('pending-warning');
                    if (!warningEl) {
                        warningEl = document.createElement('div');
                        warningEl.id = 'pending-warning';
                        warningEl.className = 'alert alert-warning mt-2';
                        warningEl.innerHTML = '<i class="fas fa-exclamation-triangle"></i> <strong>BLOCKED:</strong> ' + data.message;
                        document.getElementById('vehicle_id').parentNode.appendChild(warningEl);
                    } else {
                        warningEl.innerHTML = '<i class="fas fa-exclamation-triangle"></i> <strong>BLOCKED:</strong> ' + data.message;
                    }
                    isTripPending = true;
                } else {
                    const warningEl = document.getElementById('pending-warning');
                    if (warningEl) warningEl.remove();
                    isTripPending = false;
                }
            })
            .catch(err => console.log('Error:', err));
    }
}

// Smart odometer - auto-fill start from last end
function handleVehicleChange() {
    const vehicleId = document.getElementById('vehicle_id').value;
    
    if (vehicleId === 'new') {
        document.getElementById('new_vehicle_fields').style.display = 'block';
        document.getElementById('new_vehicle_type_field').style.display = 'block';
    } else if (vehicleId) {
        document.getElementById('new_vehicle_fields').style.display = 'none';
        document.getElementById('new_vehicle_type_field').style.display = 'none';
        
        // Get last end odometer for this vehicle
        fetch('../get_last_odometer.php?vehicle_id=' + vehicleId + '&type=tripper')
            .then(response => response.json())
            .then(data => {
                if (data.success && data.odometer) {
                    document.getElementById('loading_start_odometer').value = data.odometer;
                }
            })
            .catch(err => console.log('Error:', err));
    }
}

function handleDriverChange() {
    const driverId = document.getElementById('driver_id').value;
    
    if (driverId === 'new') {
        document.querySelectorAll('.new-driver-field').forEach(el => el.style.display = 'block');
    } else {
        document.querySelectorAll('.new-driver-field').forEach(el => el.style.display = 'none');
    }
}

// Handle vehicle type change for custom entry
function handleVehicleTypeChange() {
    const vehicleTypeSelect = document.getElementById('new_vehicle_type_select');
    const customInput = document.getElementById('new_vehicle_type_custom');
    
    if (vehicleTypeSelect && customInput) {
        if (vehicleTypeSelect.value === 'other') {
            customInput.style.display = 'block';
            customInput.setAttribute('required', 'required');
        } else {
            customInput.style.display = 'none';
            customInput.removeAttribute('required');
        }
    }
}

// Handle deployed from change
document.getElementById('deployed_from_id').addEventListener('change', function() {
    if (this.value === 'new') {
        document.getElementById('new_deployed_field').style.display = 'block';
    } else {
        document.getElementById('new_deployed_field').style.display = 'none';
    }
});

// Handle project change
function handleProjectChange() {
    const projectId = document.getElementById('project_id').value;
    
    if (projectId === 'new') {
        document.getElementById('new_project_fields').style.display = 'block';
        document.getElementById('new_project_code').style.display = 'block';
    } else {
        document.getElementById('new_project_fields').style.display = 'none';
        document.getElementById('new_project_code').style.display = 'none';
    }
}

// Handle group change
function handleGroupChange() {
    const groupId = document.getElementById('group_id').value;
    
    if (groupId === 'new') {
        document.getElementById('new_group_fields').style.display = 'block';
    } else {
        document.getElementById('new_group_fields').style.display = 'none';
    }
}
</script>

<?php include __DIR__ . '/../includes/footer.php'; ?>
