<?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 = '';

// 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 . '/tripper/');
    exit;
}

// Get existing record with join for collector names
$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 . '/tripper/');
    exit;
}

// Access Control Logic
$canEditLoading = (hasRole('admin') || (isset($record['loading_collector_id']) && $user['id'] == $record['loading_collector_id']));
$canEditUnloading = (hasRole('admin') || (isset($record['unloading_collector_id']) && $user['id'] == $record['unloading_collector_id']));

// If someone is completing a pending trip, they should be able to edit unloading
if (!$record['unloading_collector_id'] && (hasRole('admin') || hasAccess('tripper_unloading_only') || hasAccess('all_modules'))) {
    $canEditUnloading = true;
}

// 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'];
}

$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') {
    // Only process fields the user is allowed to edit
    $updateData = [];
    $sqlParts = [];
    
    if ($canEditLoading) {
        $loadingFields = [
            'project_id', 'deployed_from_id', 'vehicle_id', 'driver_id', 'created_date', 
            'work_location', 'entry_location', 'group_id', 'material_type', 'quantity_weight',
            'loading_location', 'loading_time', 'loading_start_odometer', 'loading_collector_address', 'loading_remarks'
        ];
        foreach ($loadingFields as $field) {
            $val = $_POST[$field] ?? $record[$field];
            $sqlParts[] = "$field = ?";
            $updateData[] = ($val === '' ? null : sanitize($val));
        }
    }
    
    if ($canEditUnloading) {
        $unloadingFields = [
            'unloading_address', 'unloading_place', 'unloading_end_odometer', 'unloading_time', 'unloading_remarks', 'status'
        ];
        foreach ($unloadingFields as $field) {
            $val = $_POST[$field] ?? $record[$field];
            $sqlParts[] = "$field = ?";
            $updateData[] = ($val === '' ? null : sanitize($val));
        }
        
        // If it was pending and now has data, set collector
        if (!$record['unloading_collector_id']) {
            $sqlParts[] = "unloading_collector_id = ?";
            $updateData[] = $user['id'];
        }
    }
    
    if (!empty($sqlParts)) {
        try {
            $sql = "UPDATE tripper_records SET " . implode(', ', $sqlParts) . " WHERE id = ?";
            $updateData[] = $id;
            
            $stmt = $pdo->prepare($sql);
            $stmt->execute($updateData);
            
            $_SESSION['success_message'] = t('msg_update_success', 'Record updated successfully!');
            header('Location: ' . SITE_URL . '/tripper/view.php?id=' . $id);
            exit;
        } catch (PDOException $e) {
            $error = "Update failed: " . $e->getMessage();
        }
    }
}

$pageTitle = "Edit Tripper Record";
?>

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

<style>
    .edit-section {
        background: rgba(255, 255, 255, 0.7);
        backdrop-filter: blur(10px);
        border-radius: 15px;
        padding: 2rem;
        margin-bottom: 2rem;
        border: 1px solid rgba(255, 255, 255, 0.3);
        box-shadow: 0 8px 32px rgba(31, 38, 135, 0.07);
    }
    .section-title {
        font-weight: 800;
        color: #1e293b;
        margin-bottom: 1.5rem;
        padding-bottom: 0.5rem;
        border-bottom: 2px solid #e2e8f0;
        display: flex;
        align-items: center;
    }
    .section-title i { margin-right: 0.75rem; }
    .locked-badge {
        font-size: 0.7rem;
        background: #fee2e2;
        color: #ef4444;
        padding: 0.2rem 0.5rem;
        border-radius: 4px;
        margin-left: 1rem;
    }
</style>

<div class="row mb-4">
    <div class="col-12">
        <div class="d-flex justify-content-between align-items-center">
            <h2 class="fw-bold"><i class="fas fa-edit text-primary me-2"></i> Edit Tripper Record</h2>
            <a href="view.php?id=<?php echo $id; ?>" class="btn btn-outline-secondary rounded-pill">
                <i class="fas fa-arrow-left me-1"></i> Back
            </a>
        </div>
    </div>
</div>

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

<form method="POST">
    <!-- Loading Information Section -->
    <div class="edit-section">
        <h5 class="section-title">
            <i class="fas fa-truck-loading text-success"></i> Loading Information
            <?php if (!$canEditLoading): ?>
            <span class="locked-badge"><i class="fas fa-lock me-1"></i> Read Only (Owned by another collector)</span>
            <?php endif; ?>
        </h5>
        
        <div class="row g-3">
            <div class="col-md-4">
                <label class="form-label small fw-bold">Project *</label>
                <select name="project_id" class="form-select" required <?php echo !$canEditLoading ? 'disabled' : ''; ?>>
                    <?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 small fw-bold">Vehicle *</label>
                <select name="vehicle_id" class="form-select" required <?php echo !$canEditLoading ? 'disabled' : ''; ?>>
                    <?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 small fw-bold">Driver *</label>
                <select name="driver_id" class="form-select" required <?php echo !$canEditLoading ? 'disabled' : ''; ?>>
                    <?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 small fw-bold">Date *</label>
                <?php if ($canEditLoading): ?>
                    <?php echo nepali_date_picker('created_date', $record['created_date'], '', 'form-control', true); ?>
                <?php else: ?>
                    <input type="text" class="form-control" value="<?php echo date_to_nepali($record['created_date']); ?>" disabled>
                <?php endif; ?>
            </div>
            <div class="col-md-4">
                <label class="form-label small fw-bold">Loading Time</label>
                <input type="time" name="loading_time" class="form-control" value="<?php echo $record['loading_time']; ?>" <?php echo !$canEditLoading ? 'readonly' : ''; ?>>
            </div>
            <div class="col-md-4">
                <label class="form-label small fw-bold">Start Odometer (KM)</label>
                <input type="number" step="0.01" name="loading_start_odometer" class="form-control" value="<?php echo $record['loading_start_odometer']; ?>" <?php echo !$canEditLoading ? 'readonly' : ''; ?>>
            </div>
            
            <div class="col-md-6">
                <label class="form-label small fw-bold">Loading Location</label>
                <input type="text" name="loading_location" class="form-control" value="<?php echo $record['loading_location']; ?>" <?php echo !$canEditLoading ? 'readonly' : ''; ?>>
            </div>
            <div class="col-md-6">
                <label class="form-label small fw-bold">Work Location</label>
                <input type="text" name="work_location" class="form-control" value="<?php echo $record['work_location']; ?>" <?php echo !$canEditLoading ? 'readonly' : ''; ?>>
            </div>
            
            <div class="col-md-4">
                <label class="form-label small fw-bold">Material Type</label>
                <input type="text" name="material_type" class="form-control" value="<?php echo $record['material_type']; ?>" <?php echo !$canEditLoading ? 'readonly' : ''; ?>>
            </div>
            <div class="col-md-4">
                <label class="form-label small fw-bold">Quantity/Weight</label>
                <input type="text" name="quantity_weight" class="form-control" value="<?php echo $record['quantity_weight']; ?>" <?php echo !$canEditLoading ? 'readonly' : ''; ?>>
            </div>
            <div class="col-md-4">
                <label class="form-label small fw-bold">Deployed From</label>
                <select name="deployed_from_id" class="form-select" <?php echo !$canEditLoading ? 'disabled' : ''; ?>>
                    <?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-12">
                <label class="form-label small fw-bold">Loading Remarks</label>
                <textarea name="loading_remarks" class="form-control" rows="2" <?php echo !$canEditLoading ? 'readonly' : ''; ?>><?php echo $record['loading_remarks']; ?></textarea>
            </div>
        </div>
    </div>

    <!-- Unloading Information Section -->
    <div class="edit-section">
        <h5 class="section-title">
            <i class="fas fa-truck text-primary"></i> Unloading Information
            <?php if (!$canEditUnloading): ?>
            <span class="locked-badge"><i class="fas fa-lock me-1"></i> Read Only</span>
            <?php endif; ?>
        </h5>
        
        <div class="row g-3">
            <div class="col-md-6">
                <label class="form-label small fw-bold">Unloading Place</label>
                <input type="text" name="unloading_place" class="form-control" value="<?php echo $record['unloading_place']; ?>" <?php echo !$canEditUnloading ? 'readonly' : ''; ?>>
            </div>
            <div class="col-md-6">
                <label class="form-label small fw-bold">Unloading Address</label>
                <input type="text" name="unloading_address" class="form-control" value="<?php echo $record['unloading_address']; ?>" <?php echo !$canEditUnloading ? 'readonly' : ''; ?>>
            </div>
            
            <div class="col-md-4">
                <label class="form-label small fw-bold">Unloading Time</label>
                <input type="time" name="unloading_time" class="form-control" value="<?php echo $record['unloading_time']; ?>" <?php echo !$canEditUnloading ? 'readonly' : ''; ?>>
            </div>
            <div class="col-md-4">
                <label class="form-label small fw-bold">End Odometer (KM)</label>
                <input type="number" step="0.01" name="unloading_end_odometer" class="form-control" value="<?php echo $record['unloading_end_odometer']; ?>" <?php echo !$canEditUnloading ? 'readonly' : ''; ?>>
            </div>
            <div class="col-md-4">
                <label class="form-label small fw-bold">Trip Status</label>
                <select name="status" class="form-select" <?php echo !$canEditUnloading ? 'disabled' : ''; ?>>
                    <option value="pending_unloading" <?php echo $record['status'] == 'pending_unloading' ? 'selected' : ''; ?>>Pending Unloading</option>
                    <option value="completed" <?php echo $record['status'] == 'completed' ? 'selected' : ''; ?>>Completed</option>
                    <option value="cancelled" <?php echo $record['status'] == 'cancelled' ? 'selected' : ''; ?>>Cancelled</option>
                </select>
            </div>
            
            <div class="col-12">
                <label class="form-label small fw-bold">Unloading Remarks</label>
                <textarea name="unloading_remarks" class="form-control" rows="2" <?php echo !$canEditUnloading ? 'readonly' : ''; ?>><?php echo $record['unloading_remarks']; ?></textarea>
            </div>
        </div>
    </div>

    <div class="d-flex gap-2 mb-5">
        <button type="submit" class="btn btn-primary px-4 py-2 rounded-pill shadow">
            <i class="fas fa-save me-1"></i> Save Changes
        </button>
        <a href="view.php?id=<?php echo $id; ?>" class="btn btn-light px-4 py-2 rounded-pill border">
            Cancel
        </a>
    </div>
</form>

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