<?php
session_start();
include 'layouts/dbconn.php';
include 'includes/menu_config.php';

// Set timezone
date_default_timezone_set('Africa/Nairobi');

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$user_id = $_SESSION['user_id'];
$user_role = $_SESSION['role_name'] ?? 'User';

// Fetch user details
$sql_user = "SELECT u.*, ur.role_name FROM users u 
             INNER JOIN user_roles ur ON u.role_id = ur.role_id 
             WHERE u.user_id = ?";
$stmt_user = $conn->prepare($sql_user);
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$user_details = $stmt_user->get_result()->fetch_assoc();

if (!$user_details) {
    header('Location: logout.php');
    exit();
}

// Create vehicle_maintenance table if it doesn't exist
$create_table_sql = "CREATE TABLE IF NOT EXISTS vehicle_maintenance (
    maintenance_id INT AUTO_INCREMENT PRIMARY KEY,
    vehicle_id INT NOT NULL,
    maintenance_type ENUM('ROUTINE', 'REPAIR', 'INSPECTION', 'EMERGENCY', 'UPGRADE') NOT NULL,
    description TEXT NOT NULL,
    cost DECIMAL(15,2) DEFAULT 0.00,
    maintenance_date DATE NOT NULL,
    next_maintenance_date DATE NULL,
    performed_by VARCHAR(255) NULL,
    status ENUM('SCHEDULED', 'IN_PROGRESS', 'COMPLETED', 'CANCELLED') DEFAULT 'SCHEDULED',
    created_by INT NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (vehicle_id) REFERENCES vehicles(vehicle_id) ON DELETE CASCADE,
    FOREIGN KEY (created_by) REFERENCES users(user_id)
)";
$conn->query($create_table_sql);

// Handle AJAX requests
if (isset($_POST['action'])) {
    header('Content-Type: application/json');
    
    switch ($_POST['action']) {
        case 'add_maintenance':
            $vehicle_id = intval($_POST['vehicle_id']);
            $maintenance_type = $_POST['maintenance_type'];
            $description = $_POST['description'];
            $cost = floatval($_POST['cost']);
            $maintenance_date = $_POST['maintenance_date'];
            $next_maintenance_date = $_POST['next_maintenance_date'] ?: null;
            $performed_by = $_POST['performed_by'];
            $status = $_POST['status'] ?? 'SCHEDULED';
            
            $insert_sql = "INSERT INTO vehicle_maintenance 
                          (vehicle_id, maintenance_type, description, cost, maintenance_date, 
                           next_maintenance_date, performed_by, status, created_by) 
                          VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
            
            $stmt = $conn->prepare($insert_sql);
            $stmt->bind_param("issdssssi", 
                $vehicle_id, $maintenance_type, $description, $cost,
                $maintenance_date, $next_maintenance_date, $performed_by, $status, $user_id
            );
            
            if ($stmt->execute()) {
                echo json_encode(['success' => true, 'message' => 'Maintenance record added successfully']);
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to add maintenance record']);
            }
            break;
            
        case 'update_maintenance':
            $maintenance_id = intval($_POST['maintenance_id']);
            $maintenance_type = $_POST['maintenance_type'];
            $description = $_POST['description'];
            $cost = floatval($_POST['cost']);
            $maintenance_date = $_POST['maintenance_date'];
            $next_maintenance_date = $_POST['next_maintenance_date'] ?: null;
            $performed_by = $_POST['performed_by'];
            $status = $_POST['status'];
            
            $update_sql = "UPDATE vehicle_maintenance SET 
                          maintenance_type = ?, description = ?, cost = ?, 
                          maintenance_date = ?, next_maintenance_date = ?, 
                          performed_by = ?, status = ?, updated_at = NOW()
                          WHERE maintenance_id = ?";
            
            $stmt = $conn->prepare($update_sql);
            $stmt->bind_param("ssdssssi", 
                $maintenance_type, $description, $cost, $maintenance_date,
                $next_maintenance_date, $performed_by, $status, $maintenance_id
            );
            
            if ($stmt->execute()) {
                echo json_encode(['success' => true, 'message' => 'Maintenance record updated successfully']);
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to update maintenance record']);
            }
            break;
            
        case 'delete_maintenance':
            $maintenance_id = intval($_POST['maintenance_id']);
            
            $delete_sql = "DELETE FROM vehicle_maintenance WHERE maintenance_id = ?";
            $stmt = $conn->prepare($delete_sql);
            $stmt->bind_param("i", $maintenance_id);
            
            if ($stmt->execute()) {
                echo json_encode(['success' => true, 'message' => 'Maintenance record deleted successfully']);
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to delete maintenance record']);
            }
            break;
            
        default:
            echo json_encode(['success' => false, 'message' => 'Invalid action']);
    }
    exit();
}

// Filter parameters
$vehicle_filter = $_GET['vehicle'] ?? '';
$type_filter = $_GET['type'] ?? '';
$status_filter = $_GET['status'] ?? '';
$date_from = $_GET['date_from'] ?? '';
$date_to = $_GET['date_to'] ?? '';

// Build WHERE clause
$where_conditions = [];
$params = [];
$param_types = '';

if ($vehicle_filter) {
    $where_conditions[] = "v.vehicle_number LIKE ?";
    $params[] = "%$vehicle_filter%";
    $param_types .= 's';
}

if ($type_filter) {
    $where_conditions[] = "vm.maintenance_type = ?";
    $params[] = $type_filter;
    $param_types .= 's';
}

if ($status_filter) {
    $where_conditions[] = "vm.status = ?";
    $params[] = $status_filter;
    $param_types .= 's';
}

if ($date_from) {
    $where_conditions[] = "vm.maintenance_date >= ?";
    $params[] = $date_from;
    $param_types .= 's';
}

if ($date_to) {
    $where_conditions[] = "vm.maintenance_date <= ?";
    $params[] = $date_to;
    $param_types .= 's';
}

$where_clause = empty($where_conditions) ? '' : 'WHERE ' . implode(' AND ', $where_conditions);

// Get maintenance records
$sql_maintenance = "
    SELECT 
        vm.*,
        v.vehicle_number,
        v.make,
        v.model,
        v.vehicle_type,
        creator.full_name as created_by_name
    FROM vehicle_maintenance vm
    LEFT JOIN vehicles v ON vm.vehicle_id = v.vehicle_id
    LEFT JOIN users creator ON vm.created_by = creator.user_id
    $where_clause
    ORDER BY vm.maintenance_date DESC";

$stmt_maintenance = $conn->prepare($sql_maintenance);
if (!empty($params)) {
    $stmt_maintenance->bind_param($param_types, ...$params);
}
$stmt_maintenance->execute();
$maintenance_result = $stmt_maintenance->get_result();

// Get summary statistics
$sql_summary = "
    SELECT 
        COUNT(*) as total_records,
        SUM(CASE WHEN vm.status = 'COMPLETED' THEN cost ELSE 0 END) as total_cost,
        SUM(CASE WHEN vm.status = 'SCHEDULED' THEN 1 ELSE 0 END) as scheduled_count,
        SUM(CASE WHEN vm.status = 'IN_PROGRESS' THEN 1 ELSE 0 END) as in_progress_count,
        SUM(CASE WHEN vm.maintenance_type = 'EMERGENCY' THEN 1 ELSE 0 END) as emergency_count,
        SUM(CASE WHEN vm.next_maintenance_date < CURDATE() AND vm.next_maintenance_date IS NOT NULL THEN 1 ELSE 0 END) as overdue_count
    FROM vehicle_maintenance vm
    LEFT JOIN vehicles v ON vm.vehicle_id = v.vehicle_id
    $where_clause";

$stmt_summary = $conn->prepare($sql_summary);
if (!empty($params)) {
    $stmt_summary->bind_param($param_types, ...$params);
}
$stmt_summary->execute();
$summary = $stmt_summary->get_result()->fetch_assoc();

// Get vehicles for dropdown
$sql_vehicles = "SELECT vehicle_id, vehicle_number, make, model, status 
                 FROM vehicles WHERE status IN ('ACTIVE', 'MAINTENANCE') 
                 ORDER BY vehicle_number";
$vehicles_result = $conn->query($sql_vehicles);

// Get upcoming maintenance (due within 30 days)
$sql_upcoming = "
    SELECT 
        vm.*,
        v.vehicle_number,
        v.make,
        v.model,
        DATEDIFF(vm.next_maintenance_date, CURDATE()) as days_until_due
    FROM vehicle_maintenance vm
    LEFT JOIN vehicles v ON vm.vehicle_id = v.vehicle_id
    WHERE vm.next_maintenance_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 30 DAY)
    AND vm.status = 'COMPLETED'
    ORDER BY vm.next_maintenance_date ASC";

$upcoming_result = $conn->query($sql_upcoming);

$conn->close();
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Vehicle Maintenance Management')); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <!-- DataTables CSS -->
    <link href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/responsive/2.5.0/css/responsive.bootstrap5.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/buttons/2.4.2/css/buttons.bootstrap5.min.css" rel="stylesheet">
    
    <!-- SweetAlert2 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css" rel="stylesheet">
    
    <!-- Remix Icons -->
    <link href="https://cdn.jsdelivr.net/npm/remixicon@3.5.0/fonts/remixicon.css" rel="stylesheet">
    
    <style>
        .maintenance-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            border: 1px solid #e3e6f0;
            transition: all 0.3s ease;
            margin-bottom: 1.5rem;
        }
        
        .maintenance-card:hover {
            box-shadow: 0 4px 15px rgba(0,0,0,0.15);
            transform: translateY(-2px);
        }
        
        .summary-card {
            background: white;
            border-radius: 15px;
            padding: 1.5rem;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            border-left: 4px solid #667eea;
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
        }
        
        .summary-card::before {
            content: '';
            position: absolute;
            top: 0;
            right: 0;
            width: 60px;
            height: 60px;
            background: rgba(102, 126, 234, 0.1);
            border-radius: 50%;
            transform: translate(20px, -20px);
        }
        
        .summary-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.15);
        }
        
        .summary-value {
            font-size: 2rem;
            font-weight: 700;
            color: #1f2937;
            margin-bottom: 0.5rem;
        }
        
        .summary-label {
            font-size: 0.875rem;
            color: #6b7280;
            text-transform: uppercase;
            letter-spacing: 0.05em;
            font-weight: 500;
        }
        
        .status-badge {
            padding: 0.35rem 0.75rem;
            border-radius: 15px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        
        .status-scheduled { background: #dbeafe; color: #1e40af; }
        .status-in_progress { background: #fef3c7; color: #d97706; }
        .status-completed { background: #d1fae5; color: #065f46; }
        .status-cancelled { background: #fee2e2; color: #991b1b; }
        
        .type-badge {
            padding: 0.25rem 0.5rem;
            border-radius: 8px;
            font-size: 0.7rem;
            font-weight: 600;
            margin: 0.1rem;
        }
        
        .type-routine { background: #e0f2fe; color: #0277bd; }
        .type-repair { background: #fff3e0; color: #ef6c00; }
        .type-inspection { background: #f3e5f5; color: #7b1fa2; }
        .type-emergency { background: #ffebee; color: #c62828; }
        .type-upgrade { background: #e8f5e8; color: #2e7d32; }
        
        .action-btn {
            padding: 0.25rem 0.5rem;
            border-radius: 6px;
            font-size: 0.75rem;
            margin: 0.1rem;
            border: none;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .btn-view { background: #e3f2fd; color: #1976d2; }
        .btn-edit { background: #fff3e0; color: #ef6c00; }
        .btn-delete { background: #ffebee; color: #c62828; }
        
        .action-btn:hover {
            transform: scale(1.05);
        }
        
        .filter-section {
            background: #f8f9fa;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
            border: 1px solid #e9ecef;
        }
        
        .create-maintenance-btn {
            background: linear-gradient(45deg, #10b981, #059669);
            border: none;
            color: white;
            padding: 0.75rem 1.5rem;
            border-radius: 10px;
            font-weight: 600;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(16,185,129,0.3);
        }
        
        .create-maintenance-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(16,185,129,0.4);
            color: white;
        }
        
        .upcoming-card {
            border: 1px solid #e5e7eb;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 0.75rem;
            transition: all 0.2s ease;
        }
        
        .upcoming-card:hover {
            border-color: #667eea;
            box-shadow: 0 2px 4px rgba(102, 126, 234, 0.1);
        }
        
        .overdue-card {
            border-color: #ef4444;
            background: #fef2f2;
        }
        
        .due-soon-card {
            border-color: #f59e0b;
            background: #fffbeb;
        }
        
        .vehicle-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: linear-gradient(45deg, #667eea, #764ba2);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            font-size: 0.875rem;
        }
        
        .cost-display {
            font-size: 1.1rem;
            font-weight: 700;
        }
        
        @media (max-width: 768px) {
            .summary-card {
                margin-bottom: 1rem;
                text-align: center;
            }
            
            .summary-value {
                font-size: 1.5rem;
            }
            
            .table-responsive {
                font-size: 0.875rem;
            }
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    
                    <!-- Page Header -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0"><i class="ri-tools-line me-2"></i>Vehicle Maintenance Management</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                                        <li class="breadcrumb-item"><a href="vehicles.php">Fleet</a></li>
                                        <li class="breadcrumb-item active">Maintenance</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Summary Cards -->
                    <div class="row mb-4">
                        <div class="col-xl-3 col-md-6">
                            <div class="summary-card" style="border-left-color: #667eea;">
                                <div class="summary-value"><?php echo number_format($summary['total_records']); ?></div>
                                <div class="summary-label">Total Records</div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="summary-card" style="border-left-color: #10b981;">
                                <div class="summary-value">KES <?php echo number_format($summary['total_cost']); ?></div>
                                <div class="summary-label">Total Cost</div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="summary-card" style="border-left-color: #f59e0b;">
                                <div class="summary-value"><?php echo number_format($summary['scheduled_count']); ?></div>
                                <div class="summary-label">Scheduled</div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="summary-card" style="border-left-color: #ef4444;">
                                <div class="summary-value"><?php echo number_format($summary['overdue_count']); ?></div>
                                <div class="summary-label">Overdue</div>
                            </div>
                        </div>
                    </div>

                    <!-- Actions and Filters -->
                    <div class="row">
                        <div class="col-12">
                            <div class="maintenance-card">
                                <div class="card-body">
                                    <div class="row align-items-center">
                                        <div class="col-md-6">
                                            <button class="btn create-maintenance-btn me-2" onclick="showCreateMaintenanceModal()">
                                                <i class="ri-add-line me-1"></i>Add Maintenance Record
                                            </button>
                                            <button class="btn btn-outline-success me-2" onclick="exportMaintenance()">
                                                <i class="ri-download-line me-1"></i>Export
                                            </button>
                                            <button class="btn btn-outline-info" onclick="scheduleMultiple()">
                                                <i class="ri-calendar-line me-1"></i>Bulk Schedule
                                            </button>
                                        </div>
                                        <div class="col-md-6 text-end">
                                            <button class="btn btn-outline-primary" type="button" data-bs-toggle="collapse" data-bs-target="#filterSection">
                                                <i class="ri-filter-3-line me-1"></i>Filters
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Filter Section -->
                    <div class="collapse" id="filterSection">
                        <div class="filter-section">
                            <form method="GET" class="row g-3">
                                <div class="col-md-2">
                                    <label for="vehicle" class="form-label">Vehicle</label>
                                    <input type="text" class="form-control" name="vehicle" id="vehicle" 
                                           placeholder="Vehicle number..." value="<?php echo htmlspecialchars($vehicle_filter); ?>">
                                </div>
                                
                                <div class="col-md-2">
                                    <label for="type" class="form-label">Type</label>
                                    <select class="form-select" name="type" id="type">
                                        <option value="">All Types</option>
                                        <option value="ROUTINE" <?php echo $type_filter == 'ROUTINE' ? 'selected' : ''; ?>>Routine</option>
                                        <option value="REPAIR" <?php echo $type_filter == 'REPAIR' ? 'selected' : ''; ?>>Repair</option>
                                        <option value="INSPECTION" <?php echo $type_filter == 'INSPECTION' ? 'selected' : ''; ?>>Inspection</option>
                                        <option value="EMERGENCY" <?php echo $type_filter == 'EMERGENCY' ? 'selected' : ''; ?>>Emergency</option>
                                        <option value="UPGRADE" <?php echo $type_filter == 'UPGRADE' ? 'selected' : ''; ?>>Upgrade</option>
                                    </select>
                                </div>
                                
                                <div class="col-md-2">
                                    <label for="status" class="form-label">Status</label>
                                    <select class="form-select" name="status" id="status">
                                        <option value="">All Status</option>
                                        <option value="SCHEDULED" <?php echo $status_filter == 'SCHEDULED' ? 'selected' : ''; ?>>Scheduled</option>
                                        <option value="IN_PROGRESS" <?php echo $status_filter == 'IN_PROGRESS' ? 'selected' : ''; ?>>In Progress</option>
                                        <option value="COMPLETED" <?php echo $status_filter == 'COMPLETED' ? 'selected' : ''; ?>>Completed</option>
                                        <option value="CANCELLED" <?php echo $status_filter == 'CANCELLED' ? 'selected' : ''; ?>>Cancelled</option>
                                    </select>
                                </div>
                                
                                <div class="col-md-2">
                                    <label for="date_from" class="form-label">Date From</label>
                                    <input type="date" class="form-control" name="date_from" id="date_from" value="<?php echo $date_from; ?>">
                                </div>
                                
                                <div class="col-md-2">
                                    <label for="date_to" class="form-label">Date To</label>
                                    <input type="date" class="form-control" name="date_to" id="date_to" value="<?php echo $date_to; ?>">
                                </div>
                                
                                <div class="col-md-2">
                                    <label class="form-label">&nbsp;</label>
                                    <button type="submit" class="btn btn-primary d-block w-100">
                                        <i class="ri-search-line"></i>
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>

                    <!-- Main Content -->
                    <div class="row">
                        <div class="col-xl-8">
                            <!-- Maintenance Records Table -->
                            <div class="maintenance-card">
                                <div class="card-header bg-transparent border-bottom">
                                    <h5 class="card-title mb-0">
                                        <i class="ri-file-list-3-line me-2"></i>Maintenance Records
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-hover" id="maintenanceTable">
                                            <thead>
                                                <tr>
                                                    <th>Vehicle</th>
                                                    <th>Type</th>
                                                    <th>Description</th>
                                                    <th>Date</th>
                                                    <th>Cost</th>
                                                    <th>Status</th>
                                                    <th>Next Due</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php while ($maintenance = $maintenance_result->fetch_assoc()): ?>
                                                <tr>
                                                    <td>
                                                        <div class="d-flex align-items-center">
                                                            <div class="vehicle-avatar me-2">
                                                                <?php echo strtoupper(substr($maintenance['vehicle_number'], 0, 2)); ?>
                                                            </div>
                                                            <div>
                                                                <div class="fw-bold"><?php echo $maintenance['vehicle_number']; ?></div>
                                                                <small class="text-muted">
                                                                    <?php echo $maintenance['make'] . ' ' . $maintenance['model']; ?>
                                                                </small>
                                                            </div>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <span class="type-badge type-<?php echo strtolower($maintenance['maintenance_type']); ?>">
                                                            <?php echo ucfirst(strtolower($maintenance['maintenance_type'])); ?>
                                                        </span>
                                                    </td>
                                                    <td>
                                                        <div class="text-truncate" style="max-width: 200px;" title="<?php echo htmlspecialchars($maintenance['description']); ?>">
                                                            <?php echo htmlspecialchars($maintenance['description']); ?>
                                                        </div>
                                                        <?php if ($maintenance['performed_by']): ?>
                                                        <small class="text-muted">by <?php echo htmlspecialchars($maintenance['performed_by']); ?></small>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td><?php echo date('M j, Y', strtotime($maintenance['maintenance_date'])); ?></td>
                                                    <td class="cost-display">KES <?php echo number_format($maintenance['cost'], 2); ?></td>
                                                    <td>
                                                        <span class="status-badge status-<?php echo strtolower($maintenance['status']); ?>">
                                                            <?php echo ucfirst(strtolower(str_replace('_', ' ', $maintenance['status']))); ?>
                                                        </span>
                                                    </td>
                                                    <td>
                                                        <?php if ($maintenance['next_maintenance_date']): ?>
                                                            <?php 
                                                            $next_date = strtotime($maintenance['next_maintenance_date']);
                                                            $today = strtotime(date('Y-m-d'));
                                                            $days_diff = ($next_date - $today) / 86400;
                                                            $text_class = $days_diff < 0 ? 'text-danger' : ($days_diff <= 7 ? 'text-warning' : '');
                                                            ?>
                                                            <span class="<?php echo $text_class; ?>">
                                                                <?php echo date('M j, Y', $next_date); ?>
                                                            </span>
                                                            <?php if ($days_diff < 0): ?>
                                                            <br><small class="text-danger">Overdue</small>
                                                            <?php elseif ($days_diff <= 7): ?>
                                                            <br><small class="text-warning">Due soon</small>
                                                            <?php endif; ?>
                                                        <?php else: ?>
                                                        <span class="text-muted">Not scheduled</span>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <div class="btn-group" role="group">
                                                            <button class="action-btn btn-view" onclick="viewMaintenance(<?php echo $maintenance['maintenance_id']; ?>)" 
                                                                    title="View Details">
                                                                <i class="ri-eye-line"></i>
                                                            </button>
                                                            <button class="action-btn btn-edit" onclick="editMaintenance(<?php echo $maintenance['maintenance_id']; ?>)" 
                                                                    title="Edit Record">
                                                                <i class="ri-edit-line"></i>
                                                            </button>
                                                            <button class="action-btn btn-delete" onclick="deleteMaintenance(<?php echo $maintenance['maintenance_id']; ?>)" 
                                                                    title="Delete Record">
                                                                <i class="ri-delete-bin-line"></i>
                                                            </button>
                                                        </div>
                                                    </td>
                                                </tr>
                                                <?php endwhile; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-4">
                            <!-- Upcoming Maintenance -->
                            <div class="maintenance-card">
                                <div class="card-header bg-transparent border-bottom">
                                    <h5 class="card-title mb-0">
                                        <i class="ri-calendar-line me-2"></i>Upcoming Maintenance
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <?php if ($upcoming_result->num_rows > 0): ?>
                                        <?php while ($upcoming = $upcoming_result->fetch_assoc()): ?>
                                        <?php 
                                        $days_until_due = $upcoming['days_until_due'];
                                        $card_class = $days_until_due < 0 ? 'overdue-card' : ($days_until_due <= 7 ? 'due-soon-card' : 'upcoming-card');
                                        ?>
                                        <div class="<?php echo $card_class; ?>">
                                            <div class="d-flex justify-content-between align-items-start">
                                                <div>
                                                    <div class="fw-bold"><?php echo $upcoming['vehicle_number']; ?></div>
                                                    <small class="text-muted"><?php echo $upcoming['make'] . ' ' . $upcoming['model']; ?></small>
                                                    <div class="mt-1">
                                                        <span class="type-badge type-<?php echo strtolower($upcoming['maintenance_type']); ?>">
                                                            <?php echo ucfirst(strtolower($upcoming['maintenance_type'])); ?>
                                                        </span>
                                                    </div>
                                                </div>
                                                <div class="text-end">
                                                    <div class="fw-bold">
                                                        <?php echo date('M j', strtotime($upcoming['next_maintenance_date'])); ?>
                                                    </div>
                                                    <small class="<?php echo $days_until_due < 0 ? 'text-danger' : ($days_until_due <= 7 ? 'text-warning' : 'text-muted'); ?>">
                                                        <?php 
                                                        if ($days_until_due < 0) {
                                                            echo abs($days_until_due) . ' days overdue';
                                                        } elseif ($days_until_due == 0) {
                                                            echo 'Due today';
                                                        } else {
                                                            echo $days_until_due . ' days';
                                                        }
                                                        ?>
                                                    </small>
                                                </div>
                                            </div>
                                        </div>
                                        <?php endwhile; ?>
                                    <?php else: ?>
                                    <div class="text-center py-4">
                                        <i class="ri-calendar-check-line fs-2 text-muted"></i>
                                        <p class="text-muted mt-2">No upcoming maintenance scheduled</p>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>

                            <!-- Quick Stats -->
                            <div class="maintenance-card">
                                <div class="card-header bg-transparent border-bottom">
                                    <h5 class="card-title mb-0">
                                        <i class="ri-bar-chart-line me-2"></i>Quick Statistics
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div class="row text-center">
                                        <div class="col-6 mb-3">
                                            <div class="border rounded p-2">
                                                <div class="fw-bold text-primary"><?php echo $summary['in_progress_count']; ?></div>
                                                <small class="text-muted">In Progress</small>
                                            </div>
                                        </div>
                                        <div class="col-6 mb-3">
                                            <div class="border rounded p-2">
                                                <div class="fw-bold text-danger"><?php echo $summary['emergency_count']; ?></div>
                                                <small class="text-muted">Emergency</small>
                                            </div>
                                        </div>
                                        <div class="col-12">
                                            <div class="border rounded p-2">
                                                <div class="fw-bold text-success">
                                                    <?php 
                                                    $completion_rate = $summary['total_records'] > 0 ? 
                                                        round((($summary['total_records'] - $summary['scheduled_count']) / $summary['total_records']) * 100, 1) : 0;
                                                    echo $completion_rate; 
                                                    ?>%
                                                </div>
                                                <small class="text-muted">Completion Rate</small>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <!-- Add/Edit Maintenance Modal -->
    <div class="modal fade" id="maintenanceModal" tabindex="-1" aria-labelledby="maintenanceModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="maintenanceModalLabel">
                        <i class="ri-tools-line me-2"></i>Add Maintenance Record
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form id="maintenanceForm">
                    <input type="hidden" id="maintenance_id" name="maintenance_id">
                    <div class="modal-body">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label for="vehicle_id" class="form-label">Vehicle *</label>
                                <select class="form-select" id="vehicle_id" name="vehicle_id" required>
                                    <option value="">Select Vehicle</option>
                                    <?php 
                                    $vehicles_result->data_seek(0);
                                    while ($vehicle = $vehicles_result->fetch_assoc()): 
                                    ?>
                                    <option value="<?php echo $vehicle['vehicle_id']; ?>">
                                        <?php echo $vehicle['vehicle_number'] . ' - ' . $vehicle['make'] . ' ' . $vehicle['model']; ?>
                                    </option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                            
                            <div class="col-md-6">
                                <label for="maintenance_type" class="form-label">Maintenance Type *</label>
                                <select class="form-select" id="maintenance_type" name="maintenance_type" required>
                                    <option value="">Select Type</option>
                                    <option value="ROUTINE">Routine Maintenance</option>
                                    <option value="REPAIR">Repair</option>
                                    <option value="INSPECTION">Inspection</option>
                                    <option value="EMERGENCY">Emergency Repair</option>
                                    <option value="UPGRADE">Upgrade</option>
                                </select>
                            </div>
                            
                            <div class="col-12">
                                <label for="description" class="form-label">Description *</label>
                                <textarea class="form-control" id="description" name="description" rows="3" 
                                         placeholder="Describe the maintenance work performed..." required></textarea>
                            </div>
                            
                            <div class="col-md-6">
                                <label for="maintenance_date" class="form-label">Maintenance Date *</label>
                                <input type="date" class="form-control" id="maintenance_date" name="maintenance_date" 
                                       value="<?php echo date('Y-m-d'); ?>" required>
                            </div>
                            
                            <div class="col-md-6">
                                <label for="cost" class="form-label">Cost (KES)</label>
                                <input type="number" class="form-control" id="cost" name="cost" 
                                       step="0.01" min="0" placeholder="0.00">
                            </div>
                            
                            <div class="col-md-6">
                                <label for="performed_by" class="form-label">Performed By</label>
                                <input type="text" class="form-control" id="performed_by" name="performed_by" 
                                       placeholder="Mechanic/Service provider name">
                            </div>
                            
                            <div class="col-md-6">
                                <label for="status" class="form-label">Status</label>
                                <select class="form-select" id="status" name="status">
                                    <option value="SCHEDULED">Scheduled</option>
                                    <option value="IN_PROGRESS">In Progress</option>
                                    <option value="COMPLETED">Completed</option>
                                    <option value="CANCELLED">Cancelled</option>
                                </select>
                            </div>
                            
                            <div class="col-md-6">
                                <label for="next_maintenance_date" class="form-label">Next Maintenance Due</label>
                                <input type="date" class="form-control" id="next_maintenance_date" name="next_maintenance_date">
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-success">
                            <i class="ri-save-line me-1"></i>Save Record
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- View Maintenance Modal -->
    <div class="modal fade" id="viewMaintenanceModal" tabindex="-1" aria-labelledby="viewMaintenanceModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="viewMaintenanceModalLabel">
                        <i class="ri-eye-line me-2"></i>Maintenance Details
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body" id="maintenanceDetails">
                    <!-- Content will be loaded via AJAX -->
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary" onclick="printMaintenanceDetails()">
                        <i class="ri-printer-line me-1"></i>Print
                    </button>
                </div>
            </div>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    
    <!-- DataTables JS -->
    <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
    <script src="https://cdn.datatables.net/responsive/2.5.0/js/dataTables.responsive.min.js"></script>
    <script src="https://cdn.datatables.net/responsive/2.5.0/js/responsive.bootstrap5.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.2/js/dataTables.buttons.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.bootstrap5.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.html5.min.js"></script>
    
    <!-- SweetAlert2 JS -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.js"></script>
    
    <script>
$(document).ready(function() {
    // Initialize DataTable
    $('#maintenanceTable').DataTable({
        responsive: true,
        pageLength: 25,
        order: [[3, 'desc']], // Sort by date
        columnDefs: [
            { targets: [4], className: 'text-end' }, // Cost column
            { targets: [7], orderable: false } // Actions column
        ],
        dom: 'Bfrtip',
        buttons: [
            {
                extend: 'excel',
                text: '<i class="ri-file-excel-line me-1"></i>Excel',
                className: 'btn btn-success btn-sm'
            },
            {
                extend: 'pdf',
                text: '<i class="ri-file-pdf-line me-1"></i>PDF', 
                className: 'btn btn-danger btn-sm'
            }
        ]
    });

    // Form handler
    $('#maintenanceForm').on('submit', handleMaintenanceForm);
});

// Show create maintenance modal
function showCreateMaintenanceModal() {
    $('#maintenanceModalLabel').html('<i class="ri-add-line me-2"></i>Add Maintenance Record');
    $('#maintenanceForm')[0].reset();
    $('#maintenance_id').val('');
    $('#maintenance_date').val(new Date().toISOString().split('T')[0]);
    $('#maintenanceModal').modal('show');
}

// Handle form submission
function handleMaintenanceForm(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    const maintenanceId = $('#maintenance_id').val();
    const action = maintenanceId ? 'update_maintenance' : 'add_maintenance';
    formData.append('action', action);
    
    const title = maintenanceId ? 'Updating Record...' : 'Adding Record...';
    
    Swal.fire({
        title: title,
        text: 'Please wait while we process your request.',
        icon: 'info',
        allowOutsideClick: false,
        showConfirmButton: false,
        didOpen: () => {
            Swal.showLoading();
        }
    });
    
    $.ajax({
        url: 'vehicle_maintenance.php',
        method: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                Swal.fire({
                    title: 'Success!',
                    text: response.message,
                    icon: 'success',
                    timer: 2000,
                    showConfirmButton: false
                }).then(() => {
                    location.reload();
                });
            } else {
                Swal.fire({
                    title: 'Error',
                    text: response.message,
                    icon: 'error'
                });
            }
        },
        error: function() {
            Swal.fire({
                title: 'Error',
                text: 'An error occurred while processing your request.',
                icon: 'error'
            });
        }
    });
}

// View maintenance details
function viewMaintenance(maintenanceId) {
    // For now, show a placeholder - in real implementation, fetch details via AJAX
    $('#maintenanceDetails').html(`
        <div class="row">
            <div class="col-md-6">
                <h6 class="text-muted mb-3">Maintenance Information</h6>
                <table class="table table-borderless">
                    <tr><td class="text-muted">Vehicle:</td><td class="fw-bold">Loading...</td></tr>
                    <tr><td class="text-muted">Type:</td><td>Loading...</td></tr>
                    <tr><td class="text-muted">Date:</td><td>Loading...</td></tr>
                    <tr><td class="text-muted">Status:</td><td>Loading...</td></tr>
                </table>
            </div>
            <div class="col-md-6">
                <h6 class="text-muted mb-3">Cost & Provider</h6>
                <table class="table table-borderless">
                    <tr><td class="text-muted">Cost:</td><td class="fw-bold">Loading...</td></tr>
                    <tr><td class="text-muted">Performed By:</td><td>Loading...</td></tr>
                    <tr><td class="text-muted">Next Due:</td><td>Loading...</td></tr>
                </table>
            </div>
            <div class="col-12">
                <h6 class="text-muted mb-3">Description</h6>
                <p>Loading maintenance details...</p>
            </div>
        </div>
    `);
    
    $('#viewMaintenanceModal').modal('show');
    
    // In real implementation, fetch details via AJAX here
}

// Edit maintenance record
function editMaintenance(maintenanceId) {
    $('#maintenanceModalLabel').html('<i class="ri-edit-line me-2"></i>Edit Maintenance Record');
    
    // In real implementation, fetch record details via AJAX and populate form
    $('#maintenance_id').val(maintenanceId);
    $('#maintenanceModal').modal('show');
}

// Delete maintenance record
function deleteMaintenance(maintenanceId) {
    Swal.fire({
        title: 'Delete Maintenance Record',
        text: 'Are you sure you want to delete this maintenance record? This action cannot be undone.',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Yes, Delete',
        cancelButtonText: 'Cancel',
        confirmButtonColor: '#d33'
    }).then((result) => {
        if (result.isConfirmed) {
            Swal.fire({
                title: 'Deleting...',
                text: 'Please wait while we delete the record.',
                icon: 'info',
                allowOutsideClick: false,
                showConfirmButton: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });
            
            $.ajax({
                url: 'vehicle_maintenance.php',
                method: 'POST',
                data: {
                    action: 'delete_maintenance',
                    maintenance_id: maintenanceId
                },
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        Swal.fire({
                            title: 'Deleted!',
                            text: response.message,
                            icon: 'success',
                            timer: 2000,
                            showConfirmButton: false
                        }).then(() => {
                            location.reload();
                        });
                    } else {
                        Swal.fire({
                            title: 'Error',
                            text: response.message,
                            icon: 'error'
                        });
                    }
                },
                error: function() {
                    Swal.fire({
                        title: 'Error',
                        text: 'An error occurred while deleting the record.',
                        icon: 'error'
                    });
                }
            });
        }
    });
}

// Export maintenance records
function exportMaintenance() {
    Swal.fire({
        title: 'Export Maintenance Records',
        html: `
            <div class="mb-3">
                <label class="form-label">Export Format:</label>
                <select class="form-select" id="exportFormat">
                    <option value="excel">Excel (.xlsx)</option>
                    <option value="pdf">PDF Report</option>
                    <option value="csv">CSV Data</option>
                </select>
            </div>
            <div class="mb-3">
                <label class="form-label">Date Range:</label>
                <div class="row">
                    <div class="col-6">
                        <input type="date" class="form-control" id="exportFromDate" 
                               value="${new Date(Date.now() - 30*24*60*60*1000).toISOString().split('T')[0]}">
                    </div>
                    <div class="col-6">
                        <input type="date" class="form-control" id="exportToDate" 
                               value="${new Date().toISOString().split('T')[0]}">
                    </div>
                </div>
            </div>
            <div class="mb-3">
                <label class="form-label">Include:</label>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" id="includeVehicleDetails" checked>
                    <label class="form-check-label" for="includeVehicleDetails">Vehicle Details</label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" id="includeCosts" checked>
                    <label class="form-check-label" for="includeCosts">Cost Analysis</label>
                </div>
            </div>
        `,
        showCancelButton: true,
        confirmButtonText: 'Export',
        preConfirm: () => {
            return {
                format: document.getElementById('exportFormat').value,
                fromDate: document.getElementById('exportFromDate').value,
                toDate: document.getElementById('exportToDate').value,
                includeVehicleDetails: document.getElementById('includeVehicleDetails').checked,
                includeCosts: document.getElementById('includeCosts').checked
            };
        }
    }).then((result) => {
        if (result.isConfirmed) {
            const { format, fromDate, toDate, includeVehicleDetails, includeCosts } = result.value;
            
            Swal.fire({
                title: 'Generating Export...',
                text: 'Please wait while we prepare your export.',
                icon: 'info',
                allowOutsideClick: false,
                showConfirmButton: false,
                didOpen: () => {
                    Swal.showLoading();
                    setTimeout(() => {
                        Swal.close();
                        
                        // Trigger download
                        const link = document.createElement('a');
                        link.href = `exports/maintenance_export.php?format=${format}&from=${fromDate}&to=${toDate}&details=${includeVehicleDetails}&costs=${includeCosts}`;
                        link.download = `maintenance_export_${new Date().toISOString().split('T')[0]}.${format}`;
                        link.click();
                        
                        Swal.fire({
                            title: 'Export Complete!',
                            text: 'Your maintenance export has been downloaded.',
                            icon: 'success',
                            timer: 2000,
                            showConfirmButton: false
                        });
                    }, 2000);
                }
            });
        }
    });
}

// Schedule multiple maintenance
function scheduleMultiple() {
    Swal.fire({
        title: 'Bulk Schedule Maintenance',
        html: `
            <div class="mb-3">
                <label class="form-label">Maintenance Type:</label>
                <select class="form-select" id="bulkType">
                    <option value="ROUTINE">Routine Maintenance</option>
                    <option value="INSPECTION">Inspection</option>
                    <option value="REPAIR">Repair</option>
                </select>
            </div>
            <div class="mb-3">
                <label class="form-label">Vehicles:</label>
                <select class="form-select" id="bulkVehicles" multiple>
                    <?php 
                    $vehicles_result->data_seek(0);
                    while ($vehicle = $vehicles_result->fetch_assoc()): 
                    ?>
                    <option value="<?php echo $vehicle['vehicle_id']; ?>">
                        <?php echo $vehicle['vehicle_number'] . ' - ' . $vehicle['make'] . ' ' . $vehicle['model']; ?>
                    </option>
                    <?php endwhile; ?>
                </select>
                <small class="form-text text-muted">Hold Ctrl/Cmd to select multiple vehicles</small>
            </div>
            <div class="mb-3">
                <label class="form-label">Scheduled Date:</label>
                <input type="date" class="form-control" id="bulkDate" 
                       value="${new Date(Date.now() + 7*24*60*60*1000).toISOString().split('T')[0]}">
            </div>
        `,
        showCancelButton: true,
        confirmButtonText: 'Schedule All',
        preConfirm: () => {
            const vehicles = Array.from(document.getElementById('bulkVehicles').selectedOptions).map(option => option.value);
            if (vehicles.length === 0) {
                Swal.showValidationMessage('Please select at least one vehicle');
                return false;
            }
            return {
                type: document.getElementById('bulkType').value,
                vehicles: vehicles,
                date: document.getElementById('bulkDate').value
            };
        }
    }).then((result) => {
        if (result.isConfirmed) {
            Swal.fire({
                title: 'Scheduling...',
                text: `Scheduling maintenance for ${result.value.vehicles.length} vehicles.`,
                icon: 'info',
                allowOutsideClick: false,
                showConfirmButton: false,
                didOpen: () => {
                    Swal.showLoading();
                    setTimeout(() => {
                        Swal.fire({
                            title: 'Scheduled!',
                            text: `Maintenance has been scheduled for ${result.value.vehicles.length} vehicles.`,
                            icon: 'success',
                            timer: 3000,
                            showConfirmButton: false
                        });
                    }, 2000);
                }
            });
        }
    });
}

// Print maintenance details
function printMaintenanceDetails() {
    window.print();
}

// Initialize tooltips
document.addEventListener('DOMContentLoaded', function () {
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });
});
</script>

    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>