<?php
/**
 * Vehicles Management Page
 * Dozar & Tripper Management System
 */

require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../includes/auth.php';

$user = getCurrentUser();
$pdo = getPDO();

// Handle add/edit/delete
if ($_SERVER['REQUEST_METHOD'] === 'POST' && hasRole('admin')) {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'add') {
        $vehicle_number = sanitize($_POST['vehicle_number'] ?? '');
        $vehicle_type   = sanitize($_POST['vehicle_type']   ?? '');
        $entity_type    = sanitize($_POST['entity_type']    ?? 'kmc');
        $vehicle_model  = sanitize($_POST['vehicle_model']  ?? '');
        $capacity       = sanitize($_POST['capacity']       ?? '');

        if ($vehicle_number && $vehicle_type) {
            $stmt = $pdo->prepare("INSERT INTO vehicles (vehicle_number, vehicle_type, entity_type, vehicle_model, capacity) VALUES (?, ?, ?, ?, ?)");
            $stmt->execute([$vehicle_number, $vehicle_type, $entity_type, $vehicle_model, $capacity]);
            showMessage(t('msg_vehicle_added', 'Vehicle added successfully!'), 'success');
        }
    } elseif ($action === 'edit') {
        $id             = $_POST['id'] ?? '';
        $vehicle_number = sanitize($_POST['vehicle_number'] ?? '');
        $vehicle_type   = sanitize($_POST['vehicle_type']   ?? '');
        $entity_type    = sanitize($_POST['entity_type']    ?? 'kmc');
        $vehicle_model  = sanitize($_POST['vehicle_model']  ?? '');
        $capacity       = sanitize($_POST['capacity']       ?? '');

        if ($id && $vehicle_number && $vehicle_type) {
            $stmt = $pdo->prepare("UPDATE vehicles SET vehicle_number=?, vehicle_type=?, entity_type=?, vehicle_model=?, capacity=? WHERE id=?");
            $stmt->execute([$vehicle_number, $vehicle_type, $entity_type, $vehicle_model, $capacity, $id]);
            showMessage(t('msg_vehicle_updated', 'Vehicle updated successfully!'), 'success');
        }
    } elseif ($action === 'delete') {
        $id = $_POST['id'] ?? '';
        if ($id) {
            $stmt = $pdo->prepare("DELETE FROM vehicles WHERE id=?");
            $stmt->execute([$id]);
            showMessage(t('msg_vehicle_deleted', 'Vehicle deleted successfully!'), 'success');
        }
    }
}

// Get all vehicles
$vehicles = $pdo->query("SELECT * FROM vehicles ORDER BY vehicle_number")->fetchAll();
?>
<?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-car"></i> Vehicles</h2>
            <?php if (hasRole('admin')): ?>
            <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addModal">
                <i class="fas fa-plus"></i> Add Vehicle
            </button>
            <?php endif; ?>
        </div>
    </div>
</div>

<?php displayMessage(); ?>

<div class="card">
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>Vehicle Number</th>
                        <th>Type</th>
                        <th>Entity</th>
                        <th>Model</th>
                        <th>Capacity</th>
                        <?php if (hasRole('admin')): ?>
                        <th>Actions</th>
                        <?php endif; ?>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($vehicles)): ?>
                    <tr>
                        <td colspan="<?php echo hasRole('admin') ? 5 : 4; ?>" class="text-center text-muted">No vehicles found</td>
                    </tr>
                    <?php else: ?>
                    <?php foreach ($vehicles as $v): ?>
                    <tr>
                        <td><?php echo $v['vehicle_number']; ?></td>
                        <td><?php echo $v['vehicle_type']; ?></td>
                        <td>
                            <?php
                            $et = $v['entity_type'] ?? 'kmc';
                            $colors = ['kmc'=>'primary','private'=>'purple','other'=>'success'];
                            $color = $colors[$et] ?? 'secondary';
                            ?>
                            <span class="badge bg-<?php echo $color; ?>"
                                  <?php if($et==='private'): ?>style="background:#6f42c1!important"<?php endif; ?>>
                                <?php echo strtoupper($et); ?>
                            </span>
                        </td>
                        <td><?php echo $v['vehicle_model'] ?? '-'; ?></td>
                        <td><?php echo $v['capacity'] ?? '-'; ?></td>
                        <?php if (hasRole('admin')): ?>
                        <td>
                            <a href="view.php?id=<?php echo $v['id']; ?>" class="btn btn-sm btn-info">
                                <i class="fas fa-eye"></i>
                            </a>
                            <button class="btn btn-sm btn-warning" data-bs-toggle="modal" data-bs-target="#editModal<?php echo $v['id']; ?>">
                                <i class="fas fa-edit"></i>
                            </button>
                            <form method="POST" style="display:inline;">
                                <input type="hidden" name="action" value="delete">
                                <input type="hidden" name="id" value="<?php echo $v['id']; ?>">
                                <button type="submit" class="btn btn-sm btn-danger" onclick="return confirm('Delete this vehicle?')">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </form>
                        </td>
                        <?php endif; ?>
                    </tr>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Add Modal -->
<?php if (hasRole('admin')): ?>
<div class="modal fade" id="addModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Add Vehicle</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="action" value="add">
                    <div class="mb-3">
                        <label class="form-label">Vehicle Number *</label>
                        <input type="text" name="vehicle_number" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Vehicle Type *</label>
                        <select name="vehicle_type" class="form-select" required>
                            <option value="">Select Type</option>
                            <option value="Dozar">Dozar</option>
                            <option value="Tripper">Tripper</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Entity *</label>
                        <select name="entity_type" class="form-select" required>
                            <option value="kmc">KMC</option>
                            <option value="private">Private</option>
                            <option value="other">Other</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Model</label>
                        <input type="text" name="vehicle_model" class="form-control">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Capacity</label>
                        <input type="text" name="capacity" class="form-control" placeholder="e.g., 5 Ton">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn-primary">Add</button>
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                </div>
            </form>
        </div>
    </div>
</div>
<?php endif; ?>

<?php if (hasRole('admin')): ?>
<?php foreach ($vehicles as $v): ?>
<div class="modal fade" id="editModal<?php echo $v['id']; ?>" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Edit Vehicle — <?php echo htmlspecialchars($v['vehicle_number']); ?></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="action" value="edit">
                    <input type="hidden" name="id" value="<?php echo $v['id']; ?>">
                    <div class="mb-3">
                        <label class="form-label">Vehicle Number *</label>
                        <input type="text" name="vehicle_number" class="form-control" required value="<?php echo htmlspecialchars($v['vehicle_number']); ?>">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Vehicle Type *</label>
                        <select name="vehicle_type" class="form-select" required>
                            <option value="Dozar"   <?php echo $v['vehicle_type']==='Dozar'   ? 'selected':'' ?>>Dozar</option>
                            <option value="Tripper" <?php echo $v['vehicle_type']==='Tripper' ? 'selected':'' ?>>Tripper</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Entity *</label>
                        <select name="entity_type" class="form-select" required>
                            <option value="kmc"     <?php echo ($v['entity_type']??'kmc')==='kmc'     ? 'selected':'' ?>>KMC</option>
                            <option value="private" <?php echo ($v['entity_type']??'')==='private' ? 'selected':'' ?>>Private</option>
                            <option value="other"   <?php echo ($v['entity_type']??'')==='other'   ? 'selected':'' ?>>Other</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Model</label>
                        <input type="text" name="vehicle_model" class="form-control" value="<?php echo htmlspecialchars($v['vehicle_model'] ?? ''); ?>">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Capacity</label>
                        <input type="text" name="capacity" class="form-control" value="<?php echo htmlspecialchars($v['capacity'] ?? ''); ?>">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn-warning">Save Changes</button>
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                </div>
            </form>
        </div>
    </div>
</div>
<?php endforeach; ?>
<?php endif; ?>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<?php include __DIR__ . '/../includes/footer.php'; ?>
