<?php
/**
 * Add Dozar Record 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'] === 'dozar_only') {
    $vehicleFilter = " AND vehicle_type = 'Dozar'";
}
$stmt = $pdo->query("SELECT * FROM vehicles WHERE is_active = 1" . $vehicleFilter . " ORDER BY vehicle_number");
while ($row = $stmt->fetch()) {
    $vehicles[$row['id']] = $row['vehicle_number'] . ' (' . $row['vehicle_type'] . ')';
}

$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[$row['id']] = $row['entity_name'];
}

$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') {
    // DEBUG: Log incoming POST data
    error_log("DEBUG: dozar/add.php POST received - project_id: " . ($_POST['project_id'] ?? 'NOT SET') . ", new_project_name: " . ($_POST['new_project_name'] ?? 'NOT SET'));
    
    $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'));
    $collector_name = sanitize($_POST['collector_name'] ?? '');
    $work_location = sanitize($_POST['work_location'] ?? '');
    $start_odometer = sanitize($_POST['start_odometer'] ?? '');
    $end_odometer = sanitize($_POST['end_odometer'] ?? '');
    $start_time = sanitize($_POST['start_time'] ?? date('H:i'));
    $end_time = sanitize($_POST['end_time'] ?? '');
    $entry_location = sanitize($_POST['entry_location'] ?? '');
    $group_id = sanitize($_POST['group_id'] ?? '');
    $remarks = sanitize($_POST['remarks'] ?? '');
    $collector_entered_address = sanitize($_POST['collector_entered_address'] ?? '');
    $gps_latitude = sanitize($_POST['gps_latitude'] ?? '');
    $gps_longitude = sanitize($_POST['gps_longitude'] ?? '');
    $gps_address = sanitize($_POST['gps_address'] ?? '');
    
    // Calculate work length
    $work_length_hours = 0;
    if ($start_odometer && $end_odometer) {
        $work_length_hours = $end_odometer - $start_odometer;
    }
    
    // Check for duplicate entry warning
    $duplicateWarning = '';
    $stmt = $pdo->prepare("SELECT id, created_date, work_location FROM dozar_records WHERE vehicle_id = ? AND created_date = ? LIMIT 1");
    $stmt->execute([$vehicle_id, $created_date]);
    $duplicate = $stmt->fetch();
    if ($duplicate) {
        $duplicateWarning = 'Warning: A record already exists for this vehicle on ' . $created_date;
    }
    
    // Validate
    if (!$project_id || !$deployed_from_id || !$vehicle_id || !$driver_id || !$work_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 creation FIRST (before INSERT)
        if ($project_id === 'new' && !empty($_POST['new_project_name']) && !empty($_POST['new_project_code'])) {
            $newProjectName = sanitize($_POST['new_project_name']);
            $newProjectCode = sanitize($_POST['new_project_code']);
            $newProjectDesc = sanitize($_POST['new_project_description'] ?? '');
            
            // Check if project_code already exists
            $stmt = $pdo->prepare("SELECT id FROM projects WHERE project_code = ?");
            $stmt->execute([$newProjectCode]);
            $existingProject = $stmt->fetch();
            if ($existingProject) {
                $error = 'A project with this code already exists. Please use a different code or select the existing project.';
            } else {
                $stmt = $pdo->prepare("INSERT INTO projects (project_name, project_code, description) VALUES (?, ?, ?)");
                $stmt->execute([$newProjectName, $newProjectCode, $newProjectDesc]);
                $project_id = $pdo->lastInsertId();
                error_log("DEBUG: Created new project with ID: " . $project_id);
            }
        }
        
        // Skip INSERT if there was an error in previous checks
        if (empty($error)) {
        
            // Handle new vehicle creation BEFORE INSERT
            if ($vehicle_id === 'new' && !empty($_POST['new_vehicle_number'])) {
                $newVehicle = sanitize($_POST['new_vehicle_number']);
                $newVehicleType = sanitize($_POST['new_vehicle_type'] ?? 'Tripper');
                
                // Handle custom vehicle type entry
                if ($newVehicleType === 'other' && !empty($_POST['new_vehicle_type_custom'])) {
                    $newVehicleType = sanitize($_POST['new_vehicle_type_custom']);
                }
                
                // Check if vehicle_number already exists
                $stmt = $pdo->prepare("SELECT id FROM vehicles WHERE vehicle_number = ?");
                $stmt->execute([$newVehicle]);
                $existingVehicle = $stmt->fetch();
                if ($existingVehicle) {
                    $error = 'A vehicle with this number already exists. Please use a different number or select the existing vehicle.';
                } else {
                    $stmt = $pdo->prepare("INSERT INTO vehicles (vehicle_number, vehicle_type) VALUES (?, ?)");
                    $stmt->execute([$newVehicle, $newVehicleType]);
                    $vehicle_id = $pdo->lastInsertId();
                }
            }
            
            // Handle new driver creation BEFORE INSERT
            if ($driver_id === 'new' && !empty($_POST['new_driver_name']) && empty($error)) {
                $newDriver = sanitize($_POST['new_driver_name']);
                $newDriverPhone = sanitize($_POST['new_driver_phone'] ?? '');
                $newDriverAddress = sanitize($_POST['new_driver_address'] ?? '');
                
                // Check if driver with same name and phone already exists
                $stmt = $pdo->prepare("SELECT id FROM drivers WHERE full_name = ? AND phone_number = ?");
                $stmt->execute([$newDriver, $newDriverPhone]);
                $existingDriver = $stmt->fetch();
                if ($existingDriver) {
                    $error = 'A driver with this name and phone already exists. Please use a different name or select the existing driver.';
                } else {
                    $stmt = $pdo->prepare("INSERT INTO drivers (full_name, phone_number, address) VALUES (?, ?, ?)");
                    $stmt->execute([$newDriver, $newDriverPhone, $newDriverAddress]);
                    $driver_id = $pdo->lastInsertId();
                }
            }
            
            // Handle new deployed from creation BEFORE INSERT
            if ($deployed_from_id === 'new' && !empty($_POST['new_deployed']) && empty($error)) {
                $newDeployed = sanitize($_POST['new_deployed']);
                
                // Check if deployed_from already exists
                $stmt = $pdo->prepare("SELECT id FROM deployed_from WHERE entity_name = ?");
                $stmt->execute([$newDeployed]);
                $existingDeployed = $stmt->fetch();
                if ($existingDeployed) {
                    $error = 'This deployed from entity already exists. Please use a different name or select the existing entity.';
                } else {
                    $stmt = $pdo->prepare("INSERT INTO deployed_from (entity_name) VALUES (?)");
                    $stmt->execute([$newDeployed]);
                    $deployed_from_id = $pdo->lastInsertId();
                }
            }
            
            // Handle new group creation BEFORE INSERT
            if ($group_id === 'new' && !empty($_POST['new_group_name']) && empty($error)) {
                $newGroupName = sanitize($_POST['new_group_name']);
                $newGroupDesc = sanitize($_POST['new_group_description'] ?? '');
                
                // Check if group already exists
                $stmt = $pdo->prepare("SELECT id FROM groups WHERE group_name = ?");
                $stmt->execute([$newGroupName]);
                $existingGroup = $stmt->fetch();
                if ($existingGroup) {
                    $error = 'A group with this name already exists. Please use a different name or select the existing group.';
                } else {
                    $stmt = $pdo->prepare("INSERT INTO groups (group_name, description) VALUES (?, ?)");
                    $stmt->execute([$newGroupName, $newGroupDesc]);
                    $group_id = $pdo->lastInsertId();
                }
            }
            
            // Skip INSERT if there was any error
            if (empty($error)) {
            
            // Handle photo upload
            $photo_path = '';
            if (isset($_FILES['photo']) && $_FILES['photo']['error'] === UPLOAD_ERR_OK) {
                $uploadDir = __DIR__ . '/../uploads/dozar/';
                if (!is_dir($uploadDir)) {
                    mkdir($uploadDir, 0755, true);
                }
                $fileExt = pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION);
                $fileName = 'dozar_' . time() . '.' . $fileExt;
                $targetPath = $uploadDir . $fileName;
                
                if (move_uploaded_file($_FILES['photo']['tmp_name'], $targetPath)) {
                    $photo_path = 'uploads/dozar/' . $fileName;
                }
            }
            
            // DEBUG: Log values before INSERT
            error_log("DEBUG: Before INSERT - project_id: '" . $project_id . "', type: " . gettype($project_id));
            
            // Insert record
            $sql = "INSERT INTO dozar_records 
                    (project_id, deployed_from_id, vehicle_id, driver_id, created_date, collector_name, 
                     work_location, work_length_hours, collector_entered_address, gps_latitude, gps_longitude, 
                     gps_address, gps_captured_at, start_odometer, end_odometer, start_time, end_time, 
                     entry_location, group_id, remarks, photo_path, created_by) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            
            $stmt = $pdo->prepare($sql);
            try {
                $stmt->execute([
                    $project_id, $deployed_from_id, $vehicle_id, $driver_id, $created_date, $collector_name,
                    $work_location, $work_length_hours, $collector_entered_address, $gps_latitude, $gps_longitude,
                    $gps_address, $gps_latitude ? date('Y-m-d H:i:s') : null, $start_odometer, $end_odometer, 
                    $start_time, $end_time, $entry_location, $group_id ?: null, $remarks, $photo_path, $user['id']
                ]);
                
                $newRecordId = $pdo->lastInsertId();
                showMessage('Dozar record added successfully!', 'success');
                redirect('add.php');

                // Log activity
                if (file_exists(__DIR__ . '/../includes/activity_log.php')) {
                    require_once __DIR__ . '/../includes/activity_log.php';
                    logActivity($pdo, 'create', 'dozar', $newRecordId, "New dozar entry: Vehicle $vehicle_id at $work_location");
                }
                
                // If new group, add to groups table
                if (!empty($_POST['new_group_name'])) {
                    $newGroupName = sanitize($_POST['new_group_name']);
                    $newGroupDesc = sanitize($_POST['new_group_description'] ?? '');
                    $stmt = $pdo->prepare("INSERT INTO groups (group_name, description) VALUES (?, ?)");
                    $stmt->execute([$newGroupName, $newGroupDesc]);
                    $group_id = $pdo->lastInsertId();
                }
                
            } catch (Exception $e) {
                $error = 'Error: ' . $e->getMessage();
            }
            } // End second if (!empty($error))
        } // End first if (!empty($error))
    } // End else validation passed
} // End POST request check

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

<?php displayMessage(); ?>

<div class="row">
    <div class="col-12">
        <h2><i class="fas fa-truck-monster"></i> <?php echo t('nav_dozar', 'Dozar'); ?> <?php echo t('action_add', 'Add Record'); ?></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.php" class="btn btn-sm btn-primary"><?php echo t('action_add_new', 'Add Another'); ?></a>
</div>
<?php endif; ?>

<form method="POST" action="" enctype="multipart/form-data" class="row g-3" onsubmit="return validateForm()">
    <!-- 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>
        <div class="input-group">
            <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 $id => $name): ?>
                <option value="<?php echo $id; ?>"><?php echo $name; ?></option>
                <?php endforeach; ?>
                <option value="new"><?php echo t('option_add_new', '+ Add New'); ?></option>
            </select>
        </div>
    </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(); checkDuplicateEntry();">
            <option value=""><?php echo t('option_select_vehicle', 'Select Vehicle'); ?></option>
            <?php foreach ($vehicles as $id => $name): ?>
            <option value="<?php echo $id; ?>"><?php echo $name; ?></option>
            <?php endforeach; ?>
            <option value="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">New 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 and Collector -->
    <div class="col-md-4">
        <label class="form-label"><?php echo t('label_date', '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"><?php echo t('label_collector_name', 'Collector Name'); ?> *</label>
        <input type="text" name="collector_name" class="form-control" value="<?php echo $user['full_name']; ?>" required>
    </div>
    
    <div class="col-md-4">
        <label class="form-label"><?php echo t('label_group', 'Group'); ?></label>
        <select name="group_id" id="group_id" class="form-select" onchange="handleGroupChange()">
            <option value=""><?php echo t('option_select_group', '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>
    
    <!-- Odometer (Hours) -->
    <div class="col-md-3">
        <label class="form-label"><?php echo t('label_start_odometer', 'Start Odometer'); ?> (<?php echo t('unit_hours', 'Hours'); ?>) *</label>
        <input type="number" step="0.01" inputmode="decimal" name="start_odometer" id="start_odometer" class="form-control" required>
    </div>
    
    <div class="col-md-3">
        <label class="form-label"><?php echo t('label_end_odometer', 'End Odometer'); ?> (<?php echo t('unit_hours', 'Hours'); ?>)</label>
        <input type="number" step="0.01" inputmode="decimal" name="end_odometer" id="end_odometer" class="form-control" oninput="calculateWorkLength()">
    </div>
    
    <div class="col-md-3">
        <label class="form-label"><?php echo t('label_work_length', 'Work Length'); ?> (<?php echo t('unit_hours', 'Hours'); ?>)</label>
        <input type="number" step="0.01" inputmode="decimal" name="work_length_hours" id="work_length_hours" class="form-control" readonly>
    </div>
    
    <div class="col-md-3">
        <label class="form-label"><?php echo t('label_start_time', 'Start Time'); ?> *</label>
        <input type="time" name="start_time" class="form-control" value="<?php echo date('H:i'); ?>" required>
    </div>
    
    <div class="col-md-3">
        <label class="form-label"><?php echo t('label_end_time', 'End Time'); ?></label>
        <input type="time" name="end_time" class="form-control">
    </div>
    
    <!-- GPS Location -->
    <div class="col-md-6">
        <label class="form-label"><?php echo t('label_gps_location', '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> <?php echo t('label_capture_gps', '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"><?php echo t('label_gps_location', 'GPS Address'); ?> (Auto-filled)</label>
        <input type="text" name="gps_address" id="gps_address" class="form-control" readonly placeholder="<?php echo t('label_address', '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="collector_entered_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"><?php echo t('label_photo', 'Photo'); ?></label>
        <input type="file" name="photo" class="form-control" accept="image/*">
    </div>
    
    <!-- Remarks -->
    <div class="col-12">
        <label class="form-label"><?php echo t('label_remarks', 'Remarks'); ?></label>
        <textarea name="remarks" class="form-control" rows="3" placeholder="<?php echo t('label_remarks', 'Any additional notes...'); ?>"></textarea>
    </div>
    
    <!-- Submit Buttons -->
    <div class="col-12">
        <button type="submit" class="btn btn-primary">
            <i class="fas fa-save"></i> <?php echo t('action_save', 'Save Record'); ?>
        </button>
        <a href="index.php" class="btn btn-secondary">
            <i class="fas fa-times"></i> <?php echo t('action_cancel', 'Cancel'); ?>
        </a>
    </div>
</form>

<script>
// Enhanced Form validation
function validateForm() {
    const startOdometer = parseFloat(document.getElementById('start_odometer').value) || 0;
    const endOdometer = parseFloat(document.getElementById('end_odometer').value) || 0;
    const workLocation = document.getElementById('work_location').value.trim();
    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 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;
    }
    
    // Check end odometer is greater than start
    if (startOdometer > 0 && endOdometer > 0 && endOdometer < startOdometer) {
        alert('End odometer must be greater than or equal to start odometer');
        document.getElementById('end_odometer').focus();
        return false;
    }
    
    // Check work location is not empty
    if (!workLocation) {
        alert('Please enter work location');
        document.getElementById('work_location').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 vehicle number format
        if (!/^[अ-हa-zA-Z0-9\s-]+$/.test(newVehicleNumber)) {
            alert('Invalid vehicle number format');
            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 vehicle + date
function checkDuplicateEntry() {
    const vehicleId = document.getElementById('vehicle_id').value;
    const createdDate = document.getElementById('created_date').value;
    
    if (vehicleId && vehicleId !== 'new' && createdDate) {
        fetch('../get_duplicate_check.php?type=dozar&vehicle_id=' + vehicleId + '&date=' + createdDate)
            .then(response => response.json())
            .then(data => {
                if (data.duplicate) {
                    // Show warning but don't block
                    let warningEl = document.getElementById('duplicate-warning');
                    if (!warningEl) {
                        warningEl = document.createElement('div');
                        warningEl.id = 'duplicate-warning';
                        warningEl.className = 'alert alert-warning mt-2';
                        warningEl.innerHTML = '<i class="fas fa-exclamation-triangle"></i> <strong>Warning:</strong> ' + data.message;
                        document.getElementById('vehicle_id').parentNode.appendChild(warningEl);
                    } else {
                        warningEl.innerHTML = '<i class="fas fa-exclamation-triangle"></i> <strong>Warning:</strong> ' + data.message;
                    }
                } else {
                    const warningEl = document.getElementById('duplicate-warning');
                    if (warningEl) warningEl.remove();
                }
            })
            .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=dozar')
            .then(response => response.json())
            .then(data => {
                if (data.success && data.odometer) {
                    document.getElementById('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';
    }
}

// Calculate work length
function calculateWorkLength() {
    const start = parseFloat(document.getElementById('start_odometer').value) || 0;
    const end = parseFloat(document.getElementById('end_odometer').value) || 0;
    const workLength = end - start;
    
    if (workLength > 0) {
        document.getElementById('work_length_hours').value = workLength.toFixed(2);
    }
}
</script>

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