<?php
/**
 * Edit 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 = '';

// Get record ID
$id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if (!$id) {
    $_SESSION['error_message'] = t('msg_error', 'Invalid record ID');
    header('Location: ' . SITE_URL . '/dozar/');
    exit;
}

// Get existing record
$stmt = $pdo->prepare("SELECT * FROM dozar_records WHERE id = ?");
$stmt->execute([$id]);
$record = $stmt->fetch();

if (!$record) {
    $_SESSION['error_message'] = t('msg_no_records', 'Record not found');
    header('Location: ' . SITE_URL . '/dozar/');
    exit;
}

// 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') {
    $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'] ?? '');
    $end_time = sanitize($_POST['end_time'] ?? '');
    $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;
    }
    
    // Validation
    $errors = [];
    if (empty($project_id)) $errors[] = t('msg_required_fields', 'Project is required');
    if (empty($vehicle_id)) $errors[] = t('msg_required_fields', 'Vehicle is required');
    if (empty($driver_id)) $errors[] = t('msg_required_fields', 'Driver is required');
    if (empty($collector_name)) $errors[] = t('msg_required_fields', 'Collector name is required');
    if (empty($work_location)) $errors[] = t('msg_required_fields', 'Work location is required');
    if (empty($start_odometer)) $errors[] = t('msg_required_fields', 'Start odometer is required');
    
    if (empty($errors)) {
        try {
            $sql = "UPDATE dozar_records SET 
                    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 = ?,
                    start_odometer = ?,
                    end_odometer = ?,
                    start_time = ?,
                    end_time = ?,
                    group_id = ?,
                    remarks = ?
                    WHERE id = ?";
            
            $stmt = $pdo->prepare($sql);
            $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 ?: null,
                $gps_longitude ?: null,
                $gps_address,
                $start_odometer,
                $end_odometer ?: null,
                $start_time,
                $end_time ?: null,
                $group_id ?: null,
                $remarks,
                $id
            ]);
            
            $_SESSION['success_message'] = t('msg_update_success', 'Record updated successfully!');
            header('Location: ' . SITE_URL . '/dozar/view.php?id=' . $id);
            exit;
            
        } catch (PDOException $e) {
            $error = t('msg_error', 'Failed to update record: ') . $e->getMessage();
        }
    } else {
        $error = implode('<br>', $errors);
    }
}

$pageTitle = t('action_edit', 'Edit Dozar Record');
?>

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

<div class="row">
    <div class="col-12">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2><i class="fas fa-edit"></i> <?php echo t('action_edit', 'Edit Dozar Record'); ?></h2>
            <a href="view.php?id=<?php echo $id; ?>" class="btn btn-secondary">
                <i class="fas fa-arrow-left"></i> <?php echo t('action_back', 'Back'); ?>
            </a>
        </div>
    </div>
</div>

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

<form method="POST" class="card">
    <div class="card-body">
        <div class="row mb-3">
            <div class="col-md-4">
                <label class="form-label"><?php echo t('label_project', 'Project'); ?> *</label>
                <select name="project_id" class="form-select" required>
                    <option value=""><?php echo t('option_select', 'Select'); ?></option>
                    <?php foreach ($projects as $pid => $pname): ?>
                    <option value="<?php echo $pid; ?>" <?php echo $record['project_id'] == $pid ? 'selected' : ''; ?>><?php echo $pname; ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-4">
                <label class="form-label"><?php echo t('label_deployed_from', 'Deployed From'); ?> *</label>
                <select name="deployed_from_id" class="form-select" required>
                    <option value=""><?php echo t('option_select', 'Select'); ?></option>
                    <?php foreach ($deployed as $did => $dname): ?>
                    <option value="<?php echo $did; ?>" <?php echo $record['deployed_from_id'] == $did ? 'selected' : ''; ?>><?php echo $dname; ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-4">
                <label class="form-label"><?php echo t('label_group', 'Group'); ?></label>
                <select name="group_id" class="form-select">
                    <option value=""><?php echo t('option_select', 'Select'); ?></option>
                    <?php foreach ($groups as $gid => $gname): ?>
                    <option value="<?php echo $gid; ?>" <?php echo $record['group_id'] == $gid ? 'selected' : ''; ?>><?php echo $gname; ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
        </div>
        
        <div class="row mb-3">
            <div class="col-md-4">
                <label class="form-label"><?php echo t('label_vehicle', 'Vehicle'); ?> *</label>
                <select name="vehicle_id" class="form-select" required>
                    <option value=""><?php echo t('option_select', 'Select'); ?></option>
                    <?php foreach ($vehicles as $vid => $vname): ?>
                    <option value="<?php echo $vid; ?>" <?php echo $record['vehicle_id'] == $vid ? 'selected' : ''; ?>><?php echo $vname; ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-4">
                <label class="form-label"><?php echo t('label_driver', 'Driver'); ?> *</label>
                <select name="driver_id" class="form-select" required>
                    <option value=""><?php echo t('option_select', 'Select'); ?></option>
                    <?php foreach ($drivers as $did => $dname): ?>
                    <option value="<?php echo $did; ?>" <?php echo $record['driver_id'] == $did ? 'selected' : ''; ?>><?php echo $dname; ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-4">
                <label class="form-label"><?php echo t('label_date', 'Date'); ?> (नेपाली) *</label>
                <?php echo nepali_date_picker('created_date', $record['created_date'], '', 'form-control', true); ?>
            </div>
        </div>
        
        <div class="row mb-3">
            <div class="col-md-6">
                <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 $record['collector_name']; ?>" required>
            </div>
            <div class="col-md-6">
                <label class="form-label"><?php echo t('label_address', 'Collector Address'); ?></label>
                <input type="text" name="collector_entered_address" class="form-control" value="<?php echo $record['collector_entered_address']; ?>">
            </div>
        </div>
        
        <div class="row mb-3">
            <div class="col-md-12">
                <label class="form-label"><?php echo t('label_work_location', 'Work Location'); ?> *</label>
                <input type="text" name="work_location" class="form-control" value="<?php echo $record['work_location']; ?>" required>
            </div>
        </div>
        
        <div class="row mb-3">
            <div class="col-md-4">
                <label class="form-label"><?php echo t('label_start_odometer', 'Start Odometer'); ?> *</label>
                <input type="number" name="start_odometer" class="form-control" step="0.01" value="<?php echo $record['start_odometer']; ?>" id="startOdometer" required onchange="calculateHours()">
            </div>
            <div class="col-md-4">
                <label class="form-label"><?php echo t('label_end_odometer', 'End Odometer'); ?></label>
                <input type="number" name="end_odometer" class="form-control" step="0.01" value="<?php echo $record['end_odometer']; ?>" id="endOdometer" onchange="calculateHours()">
            </div>
            <div class="col-md-4">
                <label class="form-label"><?php echo t('label_work_length', 'Work Length (Hours)'); ?></label>
                <input type="text" class="form-control" value="<?php echo number_format($record['work_length_hours'], 2); ?>" id="workLength" readonly>
            </div>
        </div>
        
        <div class="row mb-3">
            <div class="col-md-4">
                <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 $record['start_time']; ?>">
            </div>
            <div class="col-md-4">
                <label class="form-label"><?php echo t('label_end_time', 'End Time'); ?></label>
                <input type="time" name="end_time" class="form-control" value="<?php echo $record['end_time']; ?>">
            </div>
            <div class="col-md-4">
                <label class="form-label"><?php echo t('label_remarks', 'Remarks'); ?></label>
                <textarea name="remarks" class="form-control" rows="2"><?php echo $record['remarks']; ?></textarea>
            </div>
        </div>
        
        <!-- GPS Location -->
        <div class="row mb-3">
            <div class="col-md-12">
                <label class="form-label"><?php echo t('label_gps_location', 'GPS Location'); ?></label>
                <div class="input-group">
                    <input type="text" name="gps_latitude" class="form-control" placeholder="Latitude" value="<?php echo $record['gps_latitude']; ?>" id="gpsLat">
                    <input type="text" name="gps_longitude" class="form-control" placeholder="Longitude" value="<?php echo $record['gps_longitude']; ?>" id="gpsLon">
                    <input type="text" name="gps_address" class="form-control" placeholder="Address" value="<?php echo $record['gps_address']; ?>" <?php echo hasRole('admin') ? '' : 'style="display:none;"'; ?>>
                    <button type="button" class="btn btn-info" onclick="captureGPS()">
                        <i class="fas fa-map-marker-alt"></i> <?php echo t('label_capture_gps', 'Capture'); ?>
                    </button>
                </div>
            </div>
        </div>
        
        <div class="row">
            <div class="col-12">
                <button type="submit" class="btn btn-primary">
                    <i class="fas fa-save"></i> <?php echo t('action_update', 'Update Record'); ?>
                </button>
                <a href="view.php?id=<?php echo $id; ?>" class="btn btn-secondary">
                    <?php echo t('action_cancel', 'Cancel'); ?>
                </a>
            </div>
        </div>
    </div>
</form>

<script>
function calculateHours() {
    var start = parseFloat(document.getElementById('startOdometer').value) || 0;
    var end = parseFloat(document.getElementById('endOdometer').value) || 0;
    var hours = end - start;
    if (hours > 0) {
        document.getElementById('workLength').value = hours.toFixed(2);
    } else {
        document.getElementById('workLength').value = '0.00';
    }
}

function captureGPS() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
            document.getElementById('gpsLat').value = position.coords.latitude.toFixed(6);
            document.getElementById('gpsLon').value = position.coords.longitude.toFixed(6);
            
            // Reverse geocode
            fetch('https://nominatim.openstreetmap.org/reverse?format=json&lat=' + position.coords.latitude + '&lon=' + position.coords.longitude)
                .then(response => response.json())
                .then(data => {
                    if (data.display_name) {
                        document.getElementById('gps_address').value = data.display_name;
                    }
                });
        }, function(error) {
            alert('GPS Error: ' + error.message);
        });
    } else {
        alert('Geolocation is not supported by this browser');
    }
}
</script>

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