<?php
/**
 * Edit Tripper 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 . '/reports/');
    exit;
}

// Get existing record
$stmt = $pdo->prepare("SELECT * FROM tripper_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 . '/reports/');
    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 = [];
$stmt = $pdo->query("SELECT * FROM vehicles WHERE is_active = 1 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'));
    $work_location = sanitize($_POST['work_location'] ?? '');
    $entry_location = sanitize($_POST['entry_location'] ?? '');
    $group_id = sanitize($_POST['group_id'] ?? '');
    $material_type = sanitize($_POST['material_type'] ?? '');
    $quantity_weight = sanitize($_POST['quantity_weight'] ?? '');
    $status = sanitize($_POST['status'] ?? 'pending_unloading');
    
    // Unloading fields (if completed)
    $unloading_place = sanitize($_POST['unloading_place'] ?? '');
    $unloading_end_odometer = sanitize($_POST['unloading_end_odometer'] ?? '');
    $unloading_remarks = sanitize($_POST['unloading_remarks'] ?? '');
    
    // 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($errors)) {
        try {
            $sql = "UPDATE tripper_records SET 
                    project_id = ?, 
                    deployed_from_id = ?, 
                    vehicle_id = ?, 
                    driver_id = ?, 
                    created_date = ?,
                    work_location = ?,
                    entry_location = ?,
                    group_id = ?,
                    material_type = ?,
                    quantity_weight = ?,
                    status = ?,
                    unloading_place = ?,
                    unloading_end_odometer = ?,
                    unloading_remarks = ?
                    WHERE id = ?";
            
            $stmt = $pdo->prepare($sql);
            $stmt->execute([
                $project_id,
                $deployed_from_id,
                $vehicle_id,
                $driver_id,
                $created_date,
                $work_location,
                $entry_location,
                $group_id ?: null,
                $material_type,
                $quantity_weight ?: null,
                $status,
                $unloading_place,
                $unloading_end_odometer ?: null,
                $unloading_remarks,
                $id
            ]);
            
            $_SESSION['success_message'] = t('msg_update_success', 'Record updated successfully!');
            header('Location: ' . SITE_URL . '/reports/tripper_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 Tripper 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 Tripper Record'); ?></h2>
            <a href="tripper_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">
        <h5 class="card-title mb-3"><?php echo t('label_record_info', 'Basic Information'); ?></h5>
        
        <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_work_location', 'Work Location'); ?></label>
                <input type="text" name="work_location" class="form-control" value="<?php echo $record['work_location']; ?>">
            </div>
            <div class="col-md-6">
                <label class="form-label"><?php echo t('label_entry_location', 'Entry Location'); ?></label>
                <input type="text" name="entry_location" class="form-control" value="<?php echo $record['entry_location']; ?>">
            </div>
        </div>
        
        <div class="row mb-3">
            <div class="col-md-4">
                <label class="form-label"><?php echo t('label_material_type', 'Material Type'); ?></label>
                <input type="text" name="material_type" class="form-control" value="<?php echo $record['material_type']; ?>">
            </div>
            <div class="col-md-4">
                <label class="form-label"><?php echo t('label_quantity', 'Quantity/Weight'); ?></label>
                <input type="number" name="quantity_weight" class="form-control" step="0.01" value="<?php echo $record['quantity_weight']; ?>">
            </div>
            <div class="col-md-4">
                <label class="form-label"><?php echo t('label_status', 'Status'); ?></label>
                <select name="status" class="form-select">
                    <option value="pending_unloading" <?php echo $record['status'] === 'pending_unloading' ? 'selected' : ''; ?>><?php echo t('status_pending_unloading', 'Pending Unloading'); ?></option>
                    <option value="completed" <?php echo $record['status'] === 'completed' ? 'selected' : ''; ?>><?php echo t('status_completed', 'Completed'); ?></option>
                    <option value="cancelled" <?php echo $record['status'] === 'cancelled' ? 'selected' : ''; ?>><?php echo t('status_cancelled', 'Cancelled'); ?></option>
                </select>
            </div>
        </div>
        
        <hr>
        <h5 class="card-title mb-3"><?php echo t('label_unloading', 'Unloading Information'); ?></h5>
        
        <div class="row mb-3">
            <div class="col-md-4">
                <label class="form-label"><?php echo t('label_unloading_location', 'Unloading Place'); ?></label>
                <input type="text" name="unloading_place" class="form-control" value="<?php echo $record['unloading_place']; ?>">
            </div>
            <div class="col-md-4">
                <label class="form-label"><?php echo t('label_end_odometer', 'End Odometer'); ?></label>
                <input type="number" name="unloading_end_odometer" class="form-control" step="0.01" value="<?php echo $record['unloading_end_odometer']; ?>">
            </div>
            <div class="col-md-4">
                <label class="form-label"><?php echo t('label_remarks', 'Unloading Remarks'); ?></label>
                <textarea name="unloading_remarks" class="form-control" rows="2"><?php echo $record['unloading_remarks']; ?></textarea>
            </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="tripper_view.php?id=<?php echo $id; ?>" class="btn btn-secondary">
                    <?php echo t('action_cancel', 'Cancel'); ?>
                </a>
            </div>
        </div>
    </div>
</form>

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