<?php

require_once dirname(__DIR__) . '/models/Asset.php';
require_once dirname(__DIR__) . '/models/Ticket.php';
require_once dirname(__DIR__) . '/models/SlaIncident.php';
require_once dirname(__DIR__) . '/../config/db.php';

class DashboardController {
    private $conn;

    public function __construct() {
        $this->conn = connectDB();
    }

    public function index() {
        // Current month and year for monthly KPIs
        $currentMonth = date('m');
        $currentYear = date('Y');

        // Fetch data for the new cards
        $totalAssets = $this->getAssetCount();
        $totalMaintenanceThisMonth = $this->getTotalMaintenanceCountByMonth($currentMonth, $currentYear);
        $assetsDamaged = $this->getAssetCountByStatus('Rusak');
        $assetsNeedRepair = $this->getAssetCountByStatus('Maintenance'); // Interpreting 'Perlu Perbaikan' as 'Maintenance' status

        echo "<div class='row row-cols-1 row-cols-md-2 row-cols-lg-2 g-3 mb-4'>"; /* Use g-3 for tighter spacing, mb-4 for bottom margin */

        // Widget 1: Total Aset
        echo "<div class='col'>
                <div class='card card-neumorphic card-accent-blue h-100'>
                    <div class='card-body'>
                        <div class='d-flex align-items-center justify-content-center'>
                            <i class='bi bi-box-seam fs-1 text-primary me-3'></i>
                            <div class='text-center'>
                                <div class='text-muted text-uppercase mb-1'>Total Aset</div>
                                <div class='fw-bold fs-2 text-primary'>{$totalAssets}</div>
                            </div>
                        </div>
                    </div>
                </div>
              </div>";

        // Widget 2: Total Aset Maintenance (Perbulan ini)
        echo "<div class='col'>
                <div class='card card-neumorphic card-accent-info h-100'>
                    <div class='card-body'>
                        <div class='d-flex align-items-center justify-content-center'>
                            <i class='bi bi-tools fs-1 text-info me-3'></i>
                            <div class='text-center'>
                                <div class='text-muted text-uppercase mb-1'>Maint. Bulan Ini</div>
                                <div class='fw-bold fs-2 text-info'>{$totalMaintenanceThisMonth}</div>
                            </div>
                        </div>
                    </div>
                </div>
              </div>";

        // Widget 3: Aset Rusak
        echo "<div class='col'>
                <div class='card card-neumorphic card-accent-danger h-100'>
                    <div class='card-body'>
                        <div class='d-flex align-items-center justify-content-center'>
                            <i class='bi bi-cone-striped fs-1 text-danger me-3'></i>
                            <div class='text-center'>
                                <div class='text-muted text-uppercase mb-1'>Aset Rusak</div>
                                <div class='fw-bold fs-2 text-danger'>{$assetsDamaged}</div>
                            </div>
                        </div>
                    </div>
                </div>
              </div>";

        // Widget 4: Aset Perlu Perbaikan (Maintenance Status)
        echo "<div class='col'>
                <div class='card card-neumorphic card-accent-warning h-100'>
                    <div class='card-body'>
                        <div class='d-flex align-items-center justify-content-center'>
                            <i class='bi bi-wrench-adjustable fs-1 text-warning me-3'></i>
                            <div class='text-center'>
                                <div class='text-muted text-uppercase mb-1'>Perlu Perbaikan</div>
                                <div class='fw-bold fs-2 text-warning'>{$assetsNeedRepair}</div>
                            </div>
                        </div>
                    </div>
                </div>
              </div>";

        echo "</div>"; // end row

        // Fetch Tiket In Progress by Vendor
        $ticketsInProgressByVendor = $this->getTicketCountByStatus(['In Progress by Vendor']);

        // Widget: Tiket In Progress by Vendor (New Card)
        echo "<div class='row row-cols-1 row-cols-md-1 g-3 mt-3'>"; // New row for this specific KPI
        echo "<div class='col-md-6 col-lg-4'>
                <div class='card card-neumorphic card-accent-warning h-100'>
                    <div class='card-body'>
                        <div class='d-flex align-items-center justify-content-center'>
                            <i class='bi bi-hourglass-split fs-1 text-warning me-3'></i>
                            <div class='text-center'>
                                <div class='text-muted text-uppercase mb-1'>Tiket In Progress (Vendor)</div>
                                <div class='fw-bold fs-2 text-warning'>{$ticketsInProgressByVendor}</div>
                            </div>
                        </div>
                    </div>
                </div>
              </div>";
        echo "</div>"; // end new row

        // Add Scan Device button for petugas role
        if (isset($_SESSION['role']) && $_SESSION['role'] === 'petugas') {
            echo "<div class='row g-3 mt-3'>"; // Changed mt-4 to mt-3, added g-3 for consistent gap
            echo "<div class='col-12'>"; // Removed mb-4 for tighter spacing
            echo "<a href='?page=scan' class='btn btn-primary btn-lg'><i class='bi bi-qr-code-scan'></i> Scan Device</a>"; // Assuming Bootstrap Icons and a QR icon
            echo "</div>";
            echo "</div>";
        }


    }

    private function getAssetCount() {
        $stmt = $this->conn->prepare("SELECT COUNT(*) as count FROM assets");
        $stmt->execute();
        return $stmt->fetch(PDO::FETCH_ASSOC)['count'];
    }

    private function getAssetCountByStatus($status) {
        $stmt = $this->conn->prepare("SELECT COUNT(*) as count FROM assets WHERE status_aset = ?");
        $stmt->bindParam(1, $status);
        $stmt->execute();
        return $stmt->fetch(PDO::FETCH_ASSOC)['count'];
    }

    private function getTicketCountByStatus(array $statuses) {
        $in = str_repeat('?,', count($statuses) - 1) . '?';
        $stmt = $this->conn->prepare("SELECT COUNT(*) as count FROM tickets WHERE status IN ($in)");
        $stmt->execute($statuses);
        return $stmt->fetch(PDO::FETCH_ASSOC)['count'];
    }
    
    private function getOpenIncidentCount() {
        $stmt = $this->conn->prepare("SELECT COUNT(*) as count FROM sla_incidents WHERE waktu_selesai IS NULL");
        $stmt->execute();
        return $stmt->fetch(PDO::FETCH_ASSOC)['count'];
    }

    private function getTotalMaintenanceCountByMonth($month, $year) {
        $start_date = date("Y-m-01", strtotime("$year-$month-01"));
        $end_date = date("Y-m-t", strtotime("$year-$month-01"));

        $stmt = $this->conn->prepare("SELECT COUNT(*) as count FROM maintenance_history WHERE tanggal_maintenance BETWEEN :start_date AND :end_date");
        $stmt->bindParam(':start_date', $start_date);
        $stmt->bindParam(':end_date', $end_date);
        $stmt->execute();
        return $stmt->fetch(PDO::FETCH_ASSOC)['count'];
    }


}
