<?php
/**
 * Add Tripper Unloading 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 = '';

// Get record ID
$id = sanitize($_GET['id'] ?? '');

if (!$id) {
    showMessage('Invalid record ID', 'danger');
    redirect('index.php');
}

// Get existing record
$stmt = $pdo->prepare("SELECT t.*, p.project_name, v.vehicle_number, dr.full_name as driver_name, df.entity_name as deployed_name
                      FROM tripper_records t
                      LEFT JOIN projects p ON t.project_id = p.id
                      LEFT JOIN vehicles v ON t.vehicle_id = v.id
                      LEFT JOIN drivers dr ON t.driver_id = dr.id
                      LEFT JOIN deployed_from df ON t.deployed_from_id = df.id
                      WHERE t.id = ?");
$stmt->execute([$id]);
$record = $stmt->fetch();

if (!$record) {
    showMessage('Record not found', 'danger');
    redirect('index.php');
}

if ($record['status'] === 'completed') {
    showMessage('This trip is already completed', 'warning');
    redirect('index.php');
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $unloading_address = sanitize($_POST['unloading_address'] ?? '');
    $unloading_place = sanitize($_POST['unloading_place'] ?? '');
    $unloading_end_odometer = sanitize($_POST['unloading_end_odometer'] ?? '');
    $unloading_time = sanitize($_POST['unloading_time'] ?? date('H:i'));
    $unloading_remarks = sanitize($_POST['unloading_remarks'] ?? '');
    $gps_latitude = sanitize($_POST['gps_latitude'] ?? '');
    $gps_longitude = sanitize($_POST['gps_longitude'] ?? '');
    $gps_address = sanitize($_POST['gps_address'] ?? '');
    
    // Validate
    if (!$unloading_address || !$unloading_end_odometer) {
        $error = 'Please fill in all required fields';
    } elseif (floatval($unloading_end_odometer) < floatval($record['loading_start_odometer'])) {
        $error = 'Error: End odometer (' . $unloading_end_odometer . ' KM) is less than Start odometer (' . $record['loading_start_odometer'] . ' KM). Please check.';
    } elseif ($unloading_time && $record['loading_time'] && $unloading_time < $record['loading_time']) {
        $error = 'Error: Unloading time (' . $unloading_time . ') cannot be earlier than Loading time (' . $record['loading_time'] . ').';
    } else {
        // 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_unload_' . time() . '.' . $fileExt;
            $targetPath = $uploadDir . $fileName;
            
            if (move_uploaded_file($_FILES['photo']['tmp_name'], $targetPath)) {
                $photo_path = 'uploads/tripper/' . $fileName;
            }
        }
        
        // Update record
        $sql = "UPDATE tripper_records SET 
                unloading_collector_id = ?,
                unloading_address = ?,
                unloading_place = ?,
                unloading_end_odometer = ?,
                unloading_gps_latitude = ?,
                unloading_gps_longitude = ?,
                unloading_gps_address = ?,
                unloading_gps_captured_at = ?,
                unloading_time = ?,
                unloading_photo_path = ?,
                unloading_remarks = ?,
                status = 'completed'
                WHERE id = ?";
        
        $stmt = $pdo->prepare($sql);
        try {
            $stmt->execute([
                $user['id'],
                $unloading_address,
                $unloading_place,
                $unloading_end_odometer,
                $gps_latitude,
                $gps_longitude,
                $gps_address,
                $gps_latitude ? date('Y-m-d H:i:s') : null,
                $unloading_time,
                $photo_path,
                $unloading_remarks,
                $id
            ]);
            
            showMessage('Unloading completed successfully!', 'success');
            redirect('index.php');

            // Log activity
            if (file_exists(__DIR__ . '/../includes/activity_log.php')) {
                require_once __DIR__ . '/../includes/activity_log.php';
                logActivity($pdo, 'complete', 'tripper', $id, "Trip completed: Unloaded at $unloading_place");
            }

        } catch (Exception $e) {
            $error = 'Error: ' . $e->getMessage();
        }
    }
}

$pageTitle = "Complete Unloading";
?>
<?php include __DIR__ . '/../includes/header.php'; ?>

<?php displayMessage(); ?>

<div class="row">
    <div class="col-12">
        <h2><i class="fas fa-truck"></i> <?php echo t('action_unloading_entry', 'Complete Unloading'); ?></h2>
    </div>
</div>

<!-- Record Info -->
<div class="card mb-4">
    <div class="card-header bg-info text-white">
        <h5 class="mb-0"><?php echo t('report_title', 'Trip Information'); ?></h5>
    </div>
    <div class="card-body">
        <div class="row">
            <div class="col-md-3">
                <strong><?php echo t('label_date', 'Date'); ?>:</strong> <?php echo date_to_nepali($record['created_date']); ?>
            </div>
            <div class="col-md-3">
                <strong><?php echo t('label_vehicle', 'Vehicle'); ?>:</strong> <?php echo $record['vehicle_number']; ?>
            </div>
            <div class="col-md-3">
                <strong><?php echo t('label_driver', 'Driver'); ?>:</strong> <?php echo $record['driver_name']; ?>
            </div>
            <div class="col-md-3">
                <strong><?php echo t('label_deployed_from', 'Deployed From'); ?>:</strong> <?php echo $record['deployed_name']; ?>
            </div>
        </div>
        <div class="row mt-2">
            <div class="col-md-3">
                <strong><?php echo t('label_loading_location', 'Loading Location'); ?>:</strong> <?php echo $record['loading_location']; ?>
            </div>
            <div class="col-md-3">
                <strong><?php echo t('label_start_odometer', 'Start Odometer'); ?>:</strong> <?php echo $record['loading_start_odometer']; ?> <?php echo t('unit_km', 'KM'); ?>
            </div>
            <div class="col-md-3">
                <strong><?php echo t('label_material_type', 'Material'); ?>:</strong> <?php echo $record['material_type']; ?>
            </div>
            <div class="col-md-3">
                <strong><?php echo t('label_project', 'Project'); ?>:</strong> <?php echo $record['project_name']; ?>
            </div>
        </div>
    </div>
</div>

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

<form method="POST" action="" enctype="multipart/form-data" class="row g-3" onsubmit="return handleFormSubmit(this)">
    <div class="col-12">
        <h5 class="border-bottom pb-2"><?php echo t('action_unloading', 'Unloading Information'); ?></h5>
    </div>
    
    <div class="col-md-6">
        <label class="form-label">Unloading Address *</label>
        <input type="text" name="unloading_address" class="form-control" placeholder="Enter unloading address" required>
    </div>
    
    <div class="col-md-6">
        <label class="form-label">Unloading Place *</label>
        <input type="text" name="unloading_place" class="form-control" placeholder="Enter unloading place" required>
    </div>
    
    <div class="col-md-4">
        <label class="form-label">End Odometer (KM) *</label>
        <input type="number" step="0.01" inputmode="decimal" name="unloading_end_odometer" id="unloading_end_odometer" class="form-control" placeholder="Enter end odometer" required>
        <div id="odometer_warning" class="text-danger small fw-bold mt-1" style="display:none;">
            <i class="fas fa-exclamation-triangle"></i> ३ डिजिटको KM आयो चेक गर्नुहोस
        </div>
    </div>
    
    <div class="col-md-4">
        <label class="form-label">Unloading Time</label>
        <input type="time" name="unloading_time" class="form-control" value="<?php echo date('H:i'); ?>">
    </div>
    
    <!-- GPS Location -->
    <div class="col-md-4">
        <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>
    
    <!-- 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="unloading_remarks" class="form-control" rows="3" placeholder="Any additional notes..."></textarea>
    </div>
    
    <!-- Submit Buttons -->
    <div class="col-12">
        <button type="submit" class="btn btn-success">
            <i class="fas fa-check"></i> Complete Unloading
        </button>
        <a href="index.php" class="btn btn-secondary">
            <i class="fas fa-times"></i> Cancel
        </a>
    </div>
</form>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        const startOdometer = parseFloat("<?php echo $record['loading_start_odometer']; ?>") || 0;
        const endOdometerInput = document.getElementById('unloading_end_odometer');
        const warningDiv = document.getElementById('odometer_warning');
        
        if (endOdometerInput && warningDiv) {
            endOdometerInput.addEventListener('input', function() {
                const endOdometer = parseFloat(this.value) || 0;
                const difference = endOdometer - startOdometer;
                
                if (difference >= 100) {
                    warningDiv.style.display = 'block';
                } else {
                    warningDiv.style.display = 'none';
                }
            });
        }
    });

    function handleFormSubmit(form) {
        const startValue = "<?php echo $record['loading_start_odometer']; ?>";
        const startOdometer = parseFloat(startValue) || 0;
        const endOdometer = parseFloat(document.getElementById('unloading_end_odometer').value) || 0;
        const loadingTime = "<?php echo $record['loading_time']; ?>";
        const unloadingTime = form.querySelector('input[name="unloading_time"]').value;

        if (endOdometer < startOdometer) {
            alert('Error: End odometer (' + endOdometer + ') is less than starting odometer (' + startOdometer + '). Please check the KM reading.');
            document.getElementById('unloading_end_odometer').focus();
            return false;
        }

        if (unloadingTime && loadingTime && unloadingTime < loadingTime) {
            alert('Error: Unloading time (' + unloadingTime + ') is earlier than loading time (' + loadingTime + ').');
            return false;
        }

        const submitBtn = form.querySelector('button[type="submit"]');
        if (submitBtn) {
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i> Completing...';
        }
        return true;
    }
</script>

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