<?php

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

class ReportController {
    private $conn;

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

    public function index() {
        echo "<h2>Laporan & Ringkasan</h2>";
        echo "<p>Halaman ini menampilkan ringkasan data dari sistem manajemen aset.</p>";

        // --- Maintenance Summary ---
        $this->maintenanceSummary();

        // --- Life Cycle Overview ---
        $this->lifeCycleOverview();
        
        // --- Depreciation ---
        $this->depreciationSummary();
    }

    private function maintenanceSummary() {
        $assetModel = new Asset($this->conn);
        $totalAssets = $assetModel->read()->rowCount();
        
        // This is a simplified query. A more optimized approach might be needed for large datasets.
        $queryMaintained = "SELECT COUNT(DISTINCT id_aset) as maintained_count FROM maintenance_history";
        $stmtMaintained = $this->conn->prepare($queryMaintained);
        $stmtMaintained->execute();
        $maintainedCount = $stmtMaintained->fetch(PDO::FETCH_ASSOC)['maintained_count'];

        $notMaintainedCount = $totalAssets - $maintainedCount;

        echo "<div class='card mb-4'>";
        echo "<div class='card-header'><h4>Ringkasan Maintenance</h4></div>";
        echo "<div class='card-body'>";
        echo "<p>Total Aset: <strong>{$totalAssets}</strong></p>";
        echo "<p>Aset Sudah Pernah di-Maintenance: <strong>{$maintainedCount}</strong></p>";
        echo "<p>Aset Belum Pernah di-Maintenance: <strong>{$notMaintainedCount}</strong></p>";
        echo "</div>";
        echo "</div>";
    }

    private function lifeCycleOverview() {
        $assetModel = new Asset($this->conn);
        $stmt = $assetModel->read();

        $expiringSoon = [];
        $expired = [];
        $threeMonthsFromNow = new DateTime();
        $threeMonthsFromNow->modify('+3 months');
        $today = new DateTime();

        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $purchaseDate = new DateTime($row['tanggal_pembelian']);
            $endOfLifeDate = (clone $purchaseDate)->modify('+' . $row['life_cycle_years'] . ' years');

            if ($endOfLifeDate < $today) {
                $expired[] = $row;
            } elseif ($endOfLifeDate <= $threeMonthsFromNow) {
                $expiringSoon[] = $row;
            }
        }
        
        echo "<div class='card mb-4'>";
        echo "<div class='card-header'><h4>Ringkasan Usia Aset (Life Cycle)</h4></div>";
        echo "<div class='card-body'>";
        echo "<p>Aset akan habis masa pakai (dalam 3 bulan): <strong>" . count($expiringSoon) . "</strong> unit</p>";
        echo "<p>Aset sudah melewati masa pakai: <strong>" . count($expired) . "</strong> unit</p>";
        // Here you could list the assets if needed
        echo "</div>";
        echo "</div>";
    }
    
    private function depreciationSummary() {
        $assetModel = new Asset($this->conn);
        $stmt = $assetModel->read();
        
        $totalBookValue = 0;
        $totalAnnualDepreciation = 0;
        
        echo "<div class='card mb-4'>";
        echo "<div class='card-header'><h4>Ringkasan Penyusutan Aset (Metode Garis Lurus)</h4></div>";
        echo "<div class='card-body'>";
        echo "<div class='table-responsive'>";
        echo "<table class='table table-sm table-bordered'>";
        echo "<thead><tr><th>Nama Aset</th><th>Harga Awal</th><th>Umur (Thn)</th><th>Penyusutan/Thn</th><th>Akumulasi</th><th>Nilai Buku</th></tr></thead>";
        echo "<tbody>";

        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $hargaAwal = floatval($row['nilai_pembelian']);
            $umurEkonomis = intval($row['life_cycle_years']);
            $nilaiResidual = 0; // Assuming zero residual value for simplicity

            if ($umurEkonomis > 0) {
                $depresiasiPerTahun = ($hargaAwal - $nilaiResidual) / $umurEkonomis;
                
                $purchaseDate = new DateTime($row['tanggal_pembelian']);
                $today = new DateTime();
                $age = $today->diff($purchaseDate)->y; // Years since purchase
                $age = min($age, $umurEkonomis); // Cap age at life cycle
                
                $akumulasiPenyusutan = $depresiasiPerTahun * $age;
                $nilaiBuku = $hargaAwal - $akumulasiPenyusutan;

                $totalBookValue += $nilaiBuku;
                $totalAnnualDepreciation += $depresiasiPerTahun;

                echo "<tr>";
                echo "<td>" . htmlspecialchars($row['nama_perangkat']) . "</td>";
                echo "<td>" . number_format($hargaAwal, 0, ',', '.') . "</td>";
                echo "<td>" . $umurEkonomis . "</td>";
                echo "<td>" . number_format($depresiasiPerTahun, 0, ',', '.') . "</td>";
                echo "<td>" . number_format($akumulasiPenyusutan, 0, ',', '.') . "</td>";
                echo "<td>" . number_format($nilaiBuku, 0, ',', '.') . "</td>";
                echo "</tr>";
            }
        }
        echo "</tbody>";
        echo "</table>";
        echo "</div>";

        echo "<hr>";
        echo "<h5>Total Nilai Buku Seluruh Aset: <strong>Rp " . number_format($totalBookValue, 0, ',', '.') . "</strong></h5>";
        echo "<h5>Total Beban Penyusutan Tahun Ini (Estimasi): <strong>Rp " . number_format($totalAnnualDepreciation, 0, ',', '.') . "</strong></h5>";
        
        echo "</div>";
        echo "</div>";
    }
}
