<?php
require_once '../includes/config.php';
if(!isset($_SESSION['admin_logged_in'])) {
    header('Location: login.php');
    exit();
}

$today = date('Y-m-d');
$tomorrow = date('Y-m-d', strtotime('+1 day'));
$current_time = date('H:i:s');

// Auto update status before loading dashboard (same as reservations.php)
$stmt = $pdo->prepare("
    UPDATE reservations 
    SET status = 'running' 
    WHERE status = 'confirmed' 
    AND pickup_date <= ? 
    AND pickup_time <= ?
");
$stmt->execute([$today, $current_time]);

$stmt = $pdo->prepare("
    UPDATE reservations 
    SET status = 'completed' 
    WHERE status = 'running' 
    AND dropoff_date <= ? 
    AND dropoff_time <= ?
");
$stmt->execute([$today, $current_time]);

// Statistika të ndryshme
$stats = [
    'total_cars' => $pdo->query("SELECT COUNT(*) FROM cars WHERE status = 'available'")->fetchColumn(),
    'total_reservations' => $pdo->query("SELECT COUNT(*) FROM reservations")->fetchColumn(),
    'pending_reservations' => $pdo->query("SELECT COUNT(*) FROM reservations WHERE status = 'pending'")->fetchColumn(),
    'confirmed_reservations' => $pdo->query("SELECT COUNT(*) FROM reservations WHERE status = 'confirmed'")->fetchColumn(),
    'running_reservations' => $pdo->query("SELECT COUNT(*) FROM reservations WHERE status = 'running'")->fetchColumn(),
    'active_reservations' => $pdo->prepare("SELECT COUNT(*) FROM reservations WHERE status = 'running'")->fetchColumn(),
    
    'pickups_today' => $pdo->prepare("SELECT COUNT(*) FROM reservations WHERE pickup_date = ? AND status NOT IN ('cancelled', 'completed')")->execute([$today]) ? $pdo->query("SELECT COUNT(*) FROM reservations WHERE pickup_date = '$today' AND status NOT IN ('cancelled', 'completed')")->fetchColumn() : 0,
    'pickups_tomorrow' => $pdo->prepare("SELECT COUNT(*) FROM reservations WHERE pickup_date = ? AND status NOT IN ('cancelled', 'completed')")->execute([$tomorrow]) ? $pdo->query("SELECT COUNT(*) FROM reservations WHERE pickup_date = '$tomorrow' AND status NOT IN ('cancelled', 'completed')")->fetchColumn() : 0,
    'dropoffs_today' => $pdo->prepare("SELECT COUNT(*) FROM reservations WHERE dropoff_date = ? AND status NOT IN ('cancelled', 'completed')")->execute([$today]) ? $pdo->query("SELECT COUNT(*) FROM reservations WHERE dropoff_date = '$today' AND status NOT IN ('cancelled', 'completed')")->fetchColumn() : 0,
    'dropoffs_tomorrow' => $pdo->prepare("SELECT COUNT(*) FROM reservations WHERE dropoff_date = ? AND status NOT IN ('cancelled', 'completed')")->execute([$tomorrow]) ? $pdo->query("SELECT COUNT(*) FROM reservations WHERE dropoff_date = '$tomorrow' AND status NOT IN ('cancelled', 'completed')")->fetchColumn() : 0,
    
    'total_revenue' => $pdo->query("SELECT COALESCE(SUM(paid_amount), 0) FROM reservations WHERE payment_status = 'paid'")->fetchColumn(),
    'pending_payments' => $pdo->query("SELECT COALESCE(SUM(balance), 0) FROM reservations WHERE balance > 0 AND status NOT IN ('cancelled', 'completed')")->fetchColumn(),
    'avg_booking_value' => $pdo->query("SELECT COALESCE(AVG(total_price), 0) FROM reservations")->fetchColumn(),
];

// Fix pickup/dropoff counts
$pickup_today_stmt = $pdo->prepare("SELECT COUNT(*) FROM reservations WHERE pickup_date = ? AND status NOT IN ('cancelled', 'completed')");
$pickup_today_stmt->execute([$today]);
$stats['pickups_today'] = (int)$pickup_today_stmt->fetchColumn();

$pickup_tomorrow_stmt = $pdo->prepare("SELECT COUNT(*) FROM reservations WHERE pickup_date = ? AND status NOT IN ('cancelled', 'completed')");
$pickup_tomorrow_stmt->execute([$tomorrow]);
$stats['pickups_tomorrow'] = (int)$pickup_tomorrow_stmt->fetchColumn();

$dropoff_today_stmt = $pdo->prepare("SELECT COUNT(*) FROM reservations WHERE dropoff_date = ? AND status NOT IN ('cancelled', 'completed')");
$dropoff_today_stmt->execute([$today]);
$stats['dropoffs_today'] = (int)$dropoff_today_stmt->fetchColumn();

$dropoff_tomorrow_stmt = $pdo->prepare("SELECT COUNT(*) FROM reservations WHERE dropoff_date = ? AND status NOT IN ('cancelled', 'completed')");
$dropoff_tomorrow_stmt->execute([$tomorrow]);
$stats['dropoffs_tomorrow'] = (int)$dropoff_tomorrow_stmt->fetchColumn();

// Active rentals - ONLY running status
$active_rentals_stmt = $pdo->prepare("
    SELECT r.*, c.brand, c.model 
    FROM reservations r 
    LEFT JOIN cars c ON r.car_id = c.id 
    WHERE r.status = 'running'
    ORDER BY r.dropoff_date ASC
");
$active_rentals_stmt->execute();
$active_rentals = $active_rentals_stmt->fetchAll();

// Today's pickups (pending or confirmed - not yet running)
$today_pickups_stmt = $pdo->prepare("
    SELECT r.*, c.brand, c.model 
    FROM reservations r 
    LEFT JOIN cars c ON r.car_id = c.id 
    WHERE r.pickup_date = ? 
    AND r.status IN ('pending', 'confirmed')
    ORDER BY r.pickup_time
");
$today_pickups_stmt->execute([$today]);
$today_pickups = $today_pickups_stmt->fetchAll();

// Today's returns (running or confirmed with dropoff today)
$today_dropoffs_stmt = $pdo->prepare("
    SELECT r.*, c.brand, c.model 
    FROM reservations r 
    LEFT JOIN cars c ON r.car_id = c.id 
    WHERE r.dropoff_date = ? 
    AND r.status IN ('running', 'confirmed')
    ORDER BY r.dropoff_time
");
$today_dropoffs_stmt->execute([$today]);
$today_dropoffs = $today_dropoffs_stmt->fetchAll();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard - Car Rental Admin</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f5f5f5; }
        
        .sidebar {
            width: 260px;
            background: #1a1a2e;
            color: white;
            position: fixed;
            left: 0;
            top: 0;
            bottom: 0;
            overflow-y: auto;
        }
        .sidebar-header { padding: 24px 20px; border-bottom: 1px solid rgba(255,255,255,0.1); }
        .sidebar-header h2 { font-size: 18px; font-weight: 600; }
        .sidebar-nav { padding: 20px 0; }
        .sidebar-nav a {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px 20px;
            color: #cbd5e1;
            text-decoration: none;
            font-size: 14px;
        }
        .sidebar-nav a i { width: 20px; }
        .sidebar-nav a:hover, .sidebar-nav a.active { background: #0066cc; color: white; }
        
        .main-content { margin-left: 260px; padding: 24px; }
        .page-header { margin-bottom: 24px; }
        .page-header h1 { font-size: 24px; font-weight: 600; }
        
        .stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 16px; margin-bottom: 24px; }
        .stat-card { background: white; padding: 16px 20px; border-radius: 12px; border: 1px solid #e5e7eb; transition: all 0.2s; cursor: pointer; }
        .stat-card:hover { transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0,0,0,0.08); }
        .stat-card .stat-icon { font-size: 28px; margin-bottom: 12px; }
        .stat-card h3 { font-size: 28px; font-weight: 700; margin-bottom: 4px; }
        .stat-card p { font-size: 13px; color: #6b7280; }
        
        .section-card { background: white; border-radius: 12px; border: 1px solid #e5e7eb; margin-bottom: 24px; overflow: hidden; }
        .section-header { padding: 16px 20px; background: #f9fafb; border-bottom: 1px solid #e5e7eb; font-weight: 600; font-size: 16px; }
        .section-header i { margin-right: 8px; color: #0066cc; }
        .data-table { width: 100%; border-collapse: collapse; }
        .data-table th, .data-table td { padding: 12px 16px; text-align: left; border-bottom: 1px solid #f0f0f0; font-size: 14px; }
        .data-table th { background: #f9fafb; font-weight: 600; }
        .status-badge { display: inline-block; padding: 4px 8px; border-radius: 4px; font-size: 12px; font-weight: 500; }
        .status-pending { background: #fef3c7; color: #92400e; }
        .status-confirmed { background: #dbeafe; color: #1e40af; }
        .status-running { background: #d1fae5; color: #065f46; }
        .status-completed { background: #e0e7ff; color: #3730a3; }
        .status-cancelled { background: #fee2e2; color: #991b1b; }
        .empty-state { text-align: center; padding: 32px; color: #6b7280; }
        .btn-view { color: #0066cc; text-decoration: none; font-size: 13px; }
        
        .two-columns {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 24px;
        }
        
        @media (max-width: 768px) {
            .sidebar { width: 100%; position: relative; height: auto; }
            .main-content { margin-left: 0; }
            .stats-grid { grid-template-columns: repeat(2, 1fr); }
            .two-columns { grid-template-columns: 1fr; }
        }
    </style>
</head>
<body>
    <div class="sidebar">
        <div class="sidebar-header"><h2><i class="fas fa-car"></i> Car Rental Admin</h2></div>
        <div class="sidebar-nav">
            <a href="dashboard.php" class="active"><i class="fas fa-tachometer-alt"></i> Dashboard</a>
            <a href="cars.php"><i class="fas fa-car"></i> Cars</a>
            <a href="create-reservation.php"><i class="fas fa-plus-square"></i> Create Reservation</a>
            <a href="reservations.php"><i class="fas fa-calendar-check"></i> Reservations</a>
            <a href="calendar.php"><i class="fas fa-calendar-alt"></i> Calendar</a>
            <a href="price-list.php"><i class="fas fa-tags"></i> Price Rules</a>
            <a href="extras.php"><i class="fas fa-cogs"></i> Extras</a>
            <a href="email-settings.php"><i class="fas fa-envelope"></i> Email Settings</a>
            <a href="settings.php"><i class="fas fa-cog"></i> Settings</a>
            <a href="manage-admins.php"><i class="fas fa-user-shield"></i> Users</a>
            <a href="clients.php"><i class="fas fa-users"></i> Clients</a>
            <a href="logout.php"><i class="fas fa-sign-out-alt"></i> Logout</a>
        </div>
    </div>
    
    <div class="main-content">
        <div class="page-header">
            <h1><i class="fas fa-tachometer-alt"></i> Dashboard Overview</h1>
            <p><?php echo date('l, d F Y'); ?></p>
        </div>
        
        <div class="stats-grid">
            <div class="stat-card" onclick="window.location.href='cars.php'">
                <div class="stat-icon"><i class="fas fa-car" style="color: #0066cc;"></i></div>
                <h3><?php echo $stats['total_cars']; ?></h3>
                <p>Available Cars</p>
            </div>
            <div class="stat-card" onclick="window.location.href='reservations.php'">
                <div class="stat-icon"><i class="fas fa-calendar-check" style="color: #10b981;"></i></div>
                <h3><?php echo $stats['total_reservations']; ?></h3>
                <p>Total Reservations</p>
            </div>
            <div class="stat-card" onclick="filterByStatus('pending')">
                <div class="stat-icon"><i class="fas fa-hourglass-half" style="color: #f59e0b;"></i></div>
                <h3><?php echo $stats['pending_reservations']; ?></h3>
                <p>Pending</p>
            </div>
            <div class="stat-card" onclick="filterByStatus('confirmed')">
                <div class="stat-icon"><i class="fas fa-check-circle" style="color: #3b82f6;"></i></div>
                <h3><?php echo $stats['confirmed_reservations']; ?></h3>
                <p>Confirmed</p>
            </div>
            <div class="stat-card" onclick="filterByStatus('running')">
                <div class="stat-icon"><i class="fas fa-play-circle" style="color: #10b981;"></i></div>
                <h3><?php echo $stats['running_reservations']; ?></h3>
                <p>Running</p>
            </div>
            <div class="stat-card" onclick="window.location.href='reservations.php?date_filter=today'">
                <div class="stat-icon"><i class="fas fa-calendar-day" style="color: #0066cc;"></i></div>
                <h3><?php echo $stats['pickups_today']; ?></h3>
                <p>Pickups Today</p>
                <small>Tomorrow: <?php echo $stats['pickups_tomorrow']; ?></small>
            </div>
            <div class="stat-card" onclick="window.location.href='reservations.php?date_filter=today'">
                <div class="stat-icon"><i class="fas fa-undo-alt" style="color: #f59e0b;"></i></div>
                <h3><?php echo $stats['dropoffs_today']; ?></h3>
                <p>Returns Today</p>
                <small>Tomorrow: <?php echo $stats['dropoffs_tomorrow']; ?></small>
            </div>
            <div class="stat-card">
                <div class="stat-icon"><i class="fas fa-euro-sign" style="color: #10b981;"></i></div>
                <h3>€<?php echo number_format($stats['total_revenue'], 2); ?></h3>
                <p>Total Revenue</p>
            </div>
        </div>
        
        <!-- Active Rentals (Running Status) -->
        <div class="section-card">
            <div class="section-header">
                <i class="fas fa-play-circle"></i> Active Rentals (Running)
                <span style="float: right; font-size: 13px; font-weight: normal;">
                    <?php echo count($active_rentals); ?> vehicle(s) currently rented
                </span>
            </div>
            <?php if(count($active_rentals) > 0): ?>
            <table class="data-table">
                <thead>
                    <tr><th>Code</th><th>Car</th><th>Customer</th><th>Pickup</th><th>Return</th><th>Status</th><th>Balance</th><th>Action</th></tr>
                </thead>
                <tbody>
                    <?php foreach($active_rentals as $r): ?>
                    <tr>
                        <td><?php echo $r['reservation_code']; ?></td>
                        <td><?php echo htmlspecialchars($r['brand'] . ' ' . $r['model']); ?></td>
                        <td><?php echo htmlspecialchars($r['customer_name']); ?><br><small><?php echo htmlspecialchars($r['customer_phone']); ?></small></td>
                        <td><?php echo date('d/m/Y', strtotime($r['pickup_date'])); ?><br><small><?php echo substr($r['pickup_time'], 0, 5); ?></small></td>
                        <td><?php echo date('d/m/Y', strtotime($r['dropoff_date'])); ?><br><small><?php echo substr($r['dropoff_time'], 0, 5); ?></small></td>
                        <td><span class="status-badge status-running">Running</span></td>
                        <td>€<?php echo number_format($r['balance'], 2); ?></td>
                        <td><a href="reservations.php?search=<?php echo $r['reservation_code']; ?>" class="btn-view">View</a></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            <?php else: ?>
            <div class="empty-state">
                <i class="fas fa-car-side" style="font-size: 40px; margin-bottom: 12px; display: block; color: #ccc;"></i>
                No active rentals at the moment.
            </div>
            <?php endif; ?>
        </div>
        
        <!-- Two columns for Today's Pickups and Returns -->
        <div class="two-columns">
            <!-- Today's Pickups -->
            <div class="section-card">
                <div class="section-header">
                    <i class="fas fa-calendar-plus"></i> Today's Pickups
                    <span style="float: right; font-size: 13px; font-weight: normal;">
                        <?php echo date('d/m/Y'); ?>
                    </span>
                </div>
                <?php if(count($today_pickups) > 0): ?>
                <table class="data-table">
                    <thead>
                        <tr><th>Time</th><th>Code</th><th>Car</th><th>Customer</th><th>Phone</th><th>Action</th></tr>
                    </thead>
                    <tbody>
                        <?php foreach($today_pickups as $r): ?>
                        <tr>
                            <td><?php echo substr($r['pickup_time'], 0, 5); ?></td>
                            <td><?php echo $r['reservation_code']; ?></td>
                            <td><?php echo htmlspecialchars($r['brand'] . ' ' . $r['model']); ?></td>
                            <td><?php echo htmlspecialchars($r['customer_name']); ?></td>
                            <td><?php echo htmlspecialchars($r['customer_phone']); ?></td>
                            <td><a href="reservations.php?search=<?php echo $r['reservation_code']; ?>" class="btn-view">View</a></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                <?php else: ?>
                <div class="empty-state">No pickups scheduled for today.</div>
                <?php endif; ?>
            </div>
            
            <!-- Today's Returns -->
            <div class="section-card">
                <div class="section-header">
                    <i class="fas fa-calendar-minus"></i> Today's Returns
                    <span style="float: right; font-size: 13px; font-weight: normal;">
                        <?php echo date('d/m/Y'); ?>
                    </span>
                </div>
                <?php if(count($today_dropoffs) > 0): ?>
                <table class="data-table">
                    <thead>
                        <tr><th>Time</th><th>Code</th><th>Car</th><th>Customer</th><th>Phone</th><th>Action</th></tr>
                    </thead>
                    <tbody>
                        <?php foreach($today_dropoffs as $r): ?>
                        <tr>
                            <td><?php echo substr($r['dropoff_time'], 0, 5); ?></td>
                            <td><?php echo $r['reservation_code']; ?></td>
                            <td><?php echo htmlspecialchars($r['brand'] . ' ' . $r['model']); ?></td>
                            <td><?php echo htmlspecialchars($r['customer_name']); ?></td>
                            <td><?php echo htmlspecialchars($r['customer_phone']); ?></td>
                            <td><a href="reservations.php?search=<?php echo $r['reservation_code']; ?>" class="btn-view">View</a></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                <?php else: ?>
                <div class="empty-state">No returns scheduled for today.</div>
                <?php endif; ?>
            </div>
        </div>
    </div>
    
    <script>
        function filterByStatus(status) {
            window.location.href = 'reservations.php?status=' + status;
        }
    </script>
</body>
</html>