<?php
/**
 * SIMPLE Dashboard Controller
 * Version simplifiée pour éviter les erreurs de dépendances
 */

class DashboardController {
    private $db;

    public function __construct() {
        $database = new Database();
        $this->db = $database->getConnection();
    }

    /**
     * Get dashboard data for mobile app (simplified stats)
     */
    public function getDashboardData() {
        try {
            $date = $_GET['date'] ?? date('Y-m-d');

            // Validate date format
            if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
                $this->sendError('Invalid date format. Use YYYY-MM-DD', 400);
            }

            // Get total active buses directly from database
            $busQuery = "SELECT COUNT(*) as count FROM buses WHERE actif = 1";
            $busStmt = $this->db->prepare($busQuery);
            $busStmt->execute();
            $busResult = $busStmt->fetch(PDO::FETCH_ASSOC);
            $totalBuses = (int)$busResult['count'];

            // Get scanned buses for the date directly from database
            $scanQuery = "SELECT COUNT(DISTINCT bus_id) as count FROM checkins WHERE checkin_date = :date AND is_valid = 1";
            $scanStmt = $this->db->prepare($scanQuery);
            $scanStmt->bindParam(':date', $date);
            $scanStmt->execute();
            $scanResult = $scanStmt->fetch(PDO::FETCH_ASSOC);
            $scannedBuses = (int)$scanResult['count'];

            $data = [
                'date' => $date,
                'total_buses' => $totalBuses,
                'scanned_buses' => $scannedBuses,
                'absent_buses' => $totalBuses - $scannedBuses
            ];

            $this->sendSuccess($data, 'Dashboard data retrieved successfully');

        } catch (Exception $e) {
            $this->sendError('Database error: ' . $e->getMessage(), 500);
        }
    }

    /**
     * Send JSON success response
     */
    private function sendSuccess($data, $message = '', $statusCode = 200) {
        http_response_code($statusCode);
        header('Content-Type: application/json; charset=utf-8');
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');

        echo json_encode([
            'success' => true,
            'message' => $message,
            'data' => $data
        ]);
        exit;
    }

    /**
     * Get active buses list with operator names
     */
    public function getActiveBuses() {
        try {
            $query = "SELECT b.matricule, o.name as operator_name
                     FROM buses b
                     LEFT JOIN operators o ON b.id_operateur = o.id
                     WHERE b.actif = 1
                     ORDER BY b.matricule ASC";

            $stmt = $this->db->prepare($query);
            $stmt->execute();
            $buses = $stmt->fetchAll(PDO::FETCH_ASSOC);

            $this->sendSuccess($buses, 'Active buses retrieved successfully');

        } catch (Exception $e) {
            $this->sendError('Database error: ' . $e->getMessage(), 500);
        }
    }

    /**
     * Get scanned buses for a specific date with full details
     */
    public function getScannedBuses() {
        try {
            $date = $_GET['date'] ?? date('Y-m-d');

            // Validate date format
            if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
                $this->sendError('Invalid date format. Use YYYY-MM-DD', 400);
            }

            $query = "SELECT
                        b.matricule,
                        o.name as operator_name,
                        c.checkin_datetime,
                        a.full_name as scanned_by
                     FROM checkins c
                     LEFT JOIN buses b ON c.bus_id = b.id
                     LEFT JOIN operators o ON b.id_operateur = o.id
                     LEFT JOIN agents a ON c.agent_id = a.id
                     WHERE DATE(c.checkin_datetime) = :date
                     AND c.is_valid = 1
                     ORDER BY c.checkin_datetime DESC";

            $stmt = $this->db->prepare($query);
            $stmt->bindParam(':date', $date);
            $stmt->execute();
            $scannedBuses = $stmt->fetchAll(PDO::FETCH_ASSOC);

            $this->sendSuccess($scannedBuses, 'Scanned buses retrieved successfully');

        } catch (Exception $e) {
            $this->sendError('Database error: ' . $e->getMessage(), 500);
        }
    }

    /**
     * Get absent buses for a specific date (active buses not scanned on that date)
     */
    public function getAbsentBuses() {
        try {
            $date = $_GET['date'] ?? date('Y-m-d');

            // Validate date format
            if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
                $this->sendError('Invalid date format. Use YYYY-MM-DD', 400);
            }

            // Get all active buses that were not scanned on the selected date
            $query = "SELECT
                        b.matricule,
                        o.name as operator_name
                     FROM buses b
                     LEFT JOIN operators o ON b.id_operateur = o.id
                     WHERE b.actif = 1
                     AND b.id NOT IN (
                         SELECT DISTINCT bus_id
                         FROM checkins
                         WHERE checkin_date = :date
                         AND is_valid = 1
                     )
                     ORDER BY b.matricule ASC";

            $stmt = $this->db->prepare($query);
            $stmt->bindParam(':date', $date);
            $stmt->execute();
            $absentBuses = $stmt->fetchAll(PDO::FETCH_ASSOC);

            $this->sendSuccess($absentBuses, 'Absent buses retrieved successfully');

        } catch (Exception $e) {
            $this->sendError('Database error: ' . $e->getMessage(), 500);
        }
    }

    /**
     * Send JSON error response
     */
    private function sendError($message, $statusCode = 400) {
        http_response_code($statusCode);
        header('Content-Type: application/json; charset=utf-8');
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');

        echo json_encode([
            'success' => false,
            'message' => $message,
            'data' => null
        ]);
        exit;
    }
}
?>
