<?php
// controllers/QuickStatsController.php

/**
 * Controller for handling Quick Stats related API requests.
 * This includes fetching various aggregate statistics for different user roles.
 */
class QuickStatsController {
    private $conn; // Database connection
    private $assignEngineerModel;
    private $companyModel;

    /**
     * Constructor to initialize the database connection.
     * @param mysqli $db The database connection object.
     */
    public function __construct($db) {
        $this->conn = $db;
        $this->assignEngineerModel = new AssignEngineer($db); 
        $this->companyModel = new Company($db); 
    }

    /**
     * Fetches quick statistics for the Admin Dashboard.
     * This method will aggregate data from various tables to provide
     * an overview of the system's current state.
     *
     * Expected data:
     * - totalUsers
     * - totalReports
     * - solvedReports
     * - unsolvedReports
     * - totalProducts
     * - totalMaintenance
     * - customerProducts
     * - configWarningTime
     *
     * This is a GET request and expects an Authorization header for authentication.
     */
    public function AdminQuickStats() {
        // --- Authentication and Authorization Check ---
        // In a real application, you would perform robust authentication and
        // authorization checks here to ensure only authorized administrators
        // can access these statistics.
        // For example:
        /*
        if (!isset($_SERVER['HTTP_AUTHORIZATION'])) {
            sendJsonResponse(['success' => false, 'message' => 'Authorization header missing.'], 401);
            return;
        }
        $token = str_replace('Bearer ', '', $_SERVER['HTTP_AUTHORIZATION']);
        // Validate token and check user role (e.g., against 'superadmin' or 'admin')
        // if (!isValidAdminToken($token, $this->conn)) {
        //     sendJsonResponse(['success' => false, 'message' => 'Unauthorized access.'], 403);
        //     return;
        // }
        */

        // --- Fetching Data ---
        // In a real application, you would query your database for actual counts.
        // For demonstration, we'll use placeholder values.

        $totalUsers = 0;
        $totalReports = 0;
        $solvedReports = 0;
        $unsolvedReports = 0;
        $totalProducts = 0;
        $totalMaintenance = 0;
        $customerProducts = 0;
        $totalCompany = 0;

        try {
            // Example: Fetch Total Users (replace with actual query)
            $usersQuery = $this->conn->query("SELECT COUNT(*) as count FROM users WHERE is_active = 1");
            if ($usersQuery) {
                $totalUsers = $usersQuery->fetch_assoc()['count'];
            }

            // Example: Fetch Total Reports (replace with actual query)
            $reportsQuery = $this->conn->query("SELECT COUNT(*) as count FROM reports");
            if ($reportsQuery) {
                $totalReports = $reportsQuery->fetch_assoc()['count'];
            }

            // Example: Fetch Solved Reports (replace with actual query)
            $solvedReportsQuery = $this->conn->query("SELECT COUNT(*) as count FROM reports WHERE status = 'completed'");
            if ($solvedReportsQuery) {
                $solvedReports = $solvedReportsQuery->fetch_assoc()['count'];
            }

            // Example: Fetch Unsolved Reports (replace with actual query)
            $unsolvedReportsQuery = $this->conn->query("SELECT COUNT(*) as count FROM reports WHERE status != 'completed'");
            if ($unsolvedReportsQuery) {
                $unsolvedReports = $unsolvedReportsQuery->fetch_assoc()['count'];
            }

            // Example: Fetch Total Products (replace with actual query)
            $productsQuery = $this->conn->query("SELECT COUNT(*) as count FROM products");
            if ($productsQuery) {
                $totalProducts = $productsQuery->fetch_assoc()['count'];
            }

            // Example: Fetch Total Maintenance (replace with actual query)
            $maintenanceQuery = $this->conn->query("SELECT COUNT(*) as count FROM maintenance_plan");
            if ($maintenanceQuery) {
                $totalMaintenance = $maintenanceQuery->fetch_assoc()['count'];
            }

            // Example: Fetch Customer Products (replace with actual query)
            $customerProductsQuery = $this->conn->query("SELECT COUNT(*) as count FROM customer_products");
            if ($customerProductsQuery) {
                $customerProducts = $customerProductsQuery->fetch_assoc()['count'];
            }
            $companyQuery = $this->conn->query("SELECT COUNT(*) as count FROM company");
            if ($companyQuery) {
                $totalCompany = $companyQuery->fetch_assoc()['count'];
            }

            // Example: Fetch Config Warning Time (replace with actual query from a config table)
            // Assuming a 'settings' or 'configurations' table with a 'key' and 'value' column

        } catch (Exception $e) {
            // Log the error and return a server error response
            error_log("Error fetching AdminQuickStats: " . $e->getMessage());
            sendJsonResponse(['success' => false, 'message' => 'Internal server error while fetching statistics.'], 500);
            return;
        }

        // --- Construct and Send Response ---
        $response = [
            'success' => true,
            'message' => 'Quick stats fetched successfully.',
            'data' => [
                'totalUsers' => $totalUsers,
                'totalReports' => $totalReports,
                'solvedReports' => $solvedReports,
                'unsolvedReports' => $unsolvedReports,
                'totalProducts' => $totalProducts,
                'totalMaintenance' => $totalMaintenance,
                'customerProducts' => $customerProducts,
                'totalCompany'=>$totalCompany,
            ]
        ];

        sendJsonResponse($response, 200);
    }

    /**
     * Fetches quick statistics for Engineer Dashboard.
     * (Placeholder - Implement real logic here)
     */
    public function EngineerQuickStats() {
        $currentUserId = getCurrentUserId();
        $totalCustomers = 0;
        $totalReports = 0;
        $solvedReports = 0;
        $unsolvedReports = 0;
        $totalMaintenance = 0;
        $customerProducts = 0;


        try {
            // Fetch Total Customers assigned to this engineer
            // Using prepared statements for security
            
            $rolesToCount = ["localcustomer", "globalcustomer"];

            // Create placeholders for the IN clause: ?, ?
            $placeholders = implode(',', array_fill(0, count($rolesToCount), '?'));
            $query = "SELECT COUNT(*) as count FROM users WHERE is_active = 1 AND role IN ($placeholders)";

        $stmt = $this->conn->prepare($query);
        if ($stmt === false) {
            error_log("Prepare failed for totalCustomers: (" . $this->conn->errno . ") " . $this->conn->error);
            // It's often better to throw an exception in a model method
            throw new Exception("Database prepare failed for customer count.");
        }

        // Dynamically create the type string (e.g., "ss" for two strings)
        $paramTypes = str_repeat('s', count($rolesToCount));

        // Bind the parameters using the splat operator to pass array values as individual arguments
        $stmt->bind_param($paramTypes, ...$rolesToCount);

        if (!$stmt->execute()) {
            error_log("Execute failed for totalCustomers: (" . $stmt->errno . ") " . $stmt->error);
            throw new Exception("Database query execution failed for customer count.");
        }

        $usersQueryResult = $stmt->get_result();
        $totalCustomers = 0; // Initialize to 0

        if ($usersQueryResult && $usersQueryResult->num_rows > 0) {
            $totalCustomers = $usersQueryResult->fetch_assoc()['count'];
        }
        $stmt->close();

        $assignedEngineer = $this->assignEngineerModel->readEngineerByCurrentDate();
        //error_log(print_r($assignedEngineer,true));
        if($assignedEngineer['engineer_id'] == $currentUserId){
            $reportsQuery = $this->conn->query("SELECT COUNT(*) as count FROM reports");
            if ($reportsQuery) {
                $totalReports = $reportsQuery->fetch_assoc()['count'];
            }

            // Example: Fetch Solved Reports (replace with actual query)
            $solvedReportsQuery = $this->conn->query("SELECT COUNT(*) as count FROM reports WHERE status = 'completed'");
            if ($solvedReportsQuery) {
                $solvedReports = $solvedReportsQuery->fetch_assoc()['count'];
            }

            // Example: Fetch Unsolved Reports (replace with actual query)
            $unsolvedReportsQuery = $this->conn->query("SELECT COUNT(*) as count FROM reports WHERE is_pick_up=0 AND status != 'completed'");
            if ($unsolvedReportsQuery) {
                $unsolvedReports = $unsolvedReportsQuery->fetch_assoc()['count'];
            }
            $maintenanceQuery = $this->conn->query("SELECT COUNT(*) as count FROM maintenance_plan");
            if ($maintenanceQuery) {
                $totalMaintenance = $maintenanceQuery->fetch_assoc()['count'];
            }

            // Example: Fetch Customer Products (replace with actual query)
            $customerProductsQuery = $this->conn->query("SELECT COUNT(*) as count FROM customer_products");
            if ($customerProductsQuery) {
                $customerProducts = $customerProductsQuery->fetch_assoc()['count'];
                error_log(":::(");
            }
            
        }else{
            $reportsQuery = $this->conn->query("SELECT COUNT(*) as count FROM reports");
            if ($reportsQuery) {
                $totalReports = $reportsQuery->fetch_assoc()['count'];
            }

            // Example: Fetch Solved Reports (replace with actual query)
            $solvedReportsQuery = $this->conn->query("SELECT COUNT(*) as count FROM reports WHERE engineer_id = $currentUserId AND status = 'completed'");
            if ($solvedReportsQuery) {
                $solvedReports = $solvedReportsQuery->fetch_assoc()['count'];
            }

            // Example: Fetch Unsolved Reports (replace with actual query)
            $unsolvedReportsQuery = $this->conn->query("SELECT COUNT(*) as count FROM reports WHERE engineer_id = $currentUserId AND status != 'completed'");
            if ($unsolvedReportsQuery) {
                $unsolvedReports = $unsolvedReportsQuery->fetch_assoc()['count'];
            }
            
        }

        } catch (Exception $e) {
            // Log the error and return a server error response
            error_log("Error fetching EngineerQuickStats: " . $e->getMessage());
            sendJsonResponse(['success' => false, 'message' => 'Internal server error while fetching statistics.'], 500);
            return;
        }

        sendJsonResponse([
            'success' => true,
            'message' => 'Engineer Quick Stats fetched successfully.',
            'data' => [
                'totalCustomers' => $totalCustomers,
                'totalReports' => $totalReports,
                'solvedReports' => $solvedReports,
                'unsolvedReports' => $unsolvedReports,
                'totalMaintenance' => $totalMaintenance,
                'customerProducts' => $customerProducts,
                 // Maps to unsolved reports for their customers
                // 'configWarningTime' => $configWarningTime, // Include if fetched
            ]
        ], 200);
    }

    /**
     * Fetches quick statistics for Customer Dashboard.
     * (Placeholder - Implement real logic here)
     */
    public function CustomerQuickStats() {
        $currentUserId = getCurrentUserId();
        $myReports = 0;
        $activeProducts = 0;
        $serviceRequests = 0; // Assuming service requests are reports with specific statuses

        // Sanitize the $id to prevent SQL injection
        $customerId = intval($currentUserId); // Ensure $id is an integer

        try {
            $company=$this->companyModel->readByCustomer($currentUserId);
            $company_id = $company['company_id'] ?? null;
            // 1. Fetch Total Reports created by this customer
            $stmt = $this->conn->prepare("SELECT COUNT(*) as count FROM reports WHERE company_id = ?");
            if ($stmt === false) {
                throw new Exception("Prepare failed for myReports: (" . $this->conn->errno . ") " . $this->conn->error);
            }
            $stmt->bind_param("i", $company_id);
            $stmt->execute();
            $reportsQueryResult = $stmt->get_result();
            if ($reportsQueryResult) {
                $myReports = $reportsQueryResult->fetch_assoc()['count'];
            }
            $stmt->close();

            // 2. Fetch Total Active Products assigned to this customer
            $stmt = $this->conn->prepare("SELECT COUNT(*) as count FROM customer_products WHERE customer_id = ?");
            if ($stmt === false) {
                throw new Exception("Prepare failed for activeProducts: (" . $this->conn->errno . ") " . $this->conn->error);
            }
            $stmt->bind_param("i", $company_id);
            $stmt->execute();
            $productsQueryResult = $stmt->get_result();
            if ($productsQueryResult) {
                $activeProducts = $productsQueryResult->fetch_assoc()['count'];
            }
            $stmt->close();

            // 3. Fetch Service Requests (e.g., reports with 'pending' or 'open' status by this customer)
            // Adjust the WHERE clause based on how you define "service requests" in your 'reports' table.
            // For example, if service requests are reports with status 'pending' or 'open'.
            $stmt = $this->conn->prepare("SELECT COUNT(*) as count FROM reports WHERE company_id = ? AND status != 'completed'");
            if ($stmt === false) {
                throw new Exception("Prepare failed for serviceRequests: (" . $this->conn->errno . ") " . $this->conn->error);
            }
            $stmt->bind_param("i", $company_id);
            $stmt->execute();
            $serviceRequestsQueryResult = $stmt->get_result();
            if ($serviceRequestsQueryResult) {
                $serviceRequests = $serviceRequestsQueryResult->fetch_assoc()['count'];
            }
            $stmt->close();
            
            $stmt = $this->conn->prepare("SELECT COUNT(*) as count FROM maintenance_plan WHERE customer_id = ? ");
            if ($stmt === false) {
                throw new Exception("Prepare failed for serviceRequests: (" . $this->conn->errno . ") " . $this->conn->error);
            }
            $stmt->bind_param("i", $customerId);
            $stmt->execute();
            $totalMaintenancePlans = $stmt->get_result();
            if ($totalMaintenancePlans) {
                $totalMaintenance = $totalMaintenancePlans->fetch_assoc()['count'];
            }
            $stmt->close();

        } catch (Exception $e) {
            // Log the error and return a server error response
            error_log("Error fetching CustomerQuickStats: " . $e->getMessage());
            sendJsonResponse(['success' => false, 'message' => 'Internal server error while fetching statistics.'], 500);
            return;
        }

        sendJsonResponse([
            'success' => true,
            'message' => 'Customer Quick Stats fetched successfully.',
            'data' => [
                'myReports' => $myReports,
                'activeProducts' => $activeProducts,
                'serviceRequests' => $serviceRequests,
                'totalMaintenance'=>$totalMaintenance,
            ]
        ], 200);
    }
}
?>
