<?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>";

        // Fetch all asset data once to avoid multiple queries
        $assetModel = new Asset($this->conn);
        $stmt = $assetModel->readPaging('', 0, 99999); // Assuming 99999 is enough to get all assets
        $allAssets = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

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

    private function maintenanceSummary($allAssets) {
        $totalAssets = count($allAssets);
        
        // 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($allAssets) {
        $expiringSoon = [];
        $expired = [];
        $threeMonthsFromNow = new DateTime();
        $threeMonthsFromNow->modify('+3 months');
        $today = new DateTime();

        foreach ($allAssets as $row) {
            $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($allAssets) {
        $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>";

        foreach ($allAssets as $row) {
            $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>";
    }
}
