<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use App\Models\BukuModel;
use App\Models\AnggotaModel;
use App\Models\PeminjamanModel;
use App\Models\PengunjungModel;

class Dashboard extends BaseController
{
    protected $buku;
    protected $anggota;
    protected $pinjam;
    protected $pengunjungModel;

    public function __construct()
    {
        $this->buku = new BukuModel();
        $this->anggota = new AnggotaModel();
        $this->pinjam = new PeminjamanModel();
        $this->pengunjungModel = new PengunjungModel();
    }

    public function index()
    {
        // 🔐 Proteksi login
        if (!session()->get('isLoggedIn')) {
            return redirect()->to('/login');
        }

        $today = date('Y-m-d');

        // ✅ FIX TANPA builder()
        $jumlahPengunjung = $this->pengunjungModel
            ->where('tanggal', $today)
            ->countAllResults();

        $sedangDipinjam = $this->pinjam
            ->where('status', 'Dipinjam')
            ->countAllResults();

        // 📊 Data grafik 7 hari terakhir
        $db = \Config\Database::connect();
        $seminggu = date('Y-m-d', strtotime('-6 days'));

        $grafikPinjam = $db
            ->table('peminjaman')
            ->select("DATE(tanggal_pinjam) as tgl, COUNT(id) as total")
            ->where('tanggal_pinjam >=', $seminggu)
            ->groupBy('DATE(tanggal_pinjam)')
            ->orderBy('tgl', 'ASC')
            ->get()
            ->getResultArray();

        $grafikDenda = $db
            ->table('peminjaman')
            ->select("DATE(tanggal_kembali) as tgl, SUM(denda) as total")
            ->where('tanggal_kembali >=', $seminggu)
            ->where('status', 'Dikembalikan')
            ->groupBy('DATE(tanggal_kembali)')
            ->orderBy('tgl', 'ASC')
            ->get()
            ->getResultArray();

        // Siapkan array 7 hari
        $tanggalArr = [];
        $totalPinjamArr = [];
        $totalDendaArr = [];

        for ($i = 6; $i >= 0; $i--) {
            $tgl = date('Y-m-d', strtotime("-$i days"));
            $tanggalArr[] = date('d-m-Y', strtotime($tgl));

            // Cari data peminjaman
            $foundPinjam = 0;
            foreach ($grafikPinjam as $g) {
                if ($g['tgl'] == $tgl) {
                    $foundPinjam = (int)$g['total'];
                    break;
                }
            }
            $totalPinjamArr[] = $foundPinjam;

            // Cari data denda
            $foundDenda = 0;
            foreach ($grafikDenda as $g) {
                if ($g['tgl'] == $tgl) {
                    $foundDenda = (int)$g['total'];
                    break;
                }
            }
            $totalDendaArr[] = $foundDenda;
        }

        $data = [
            'jumlahBuku'     => $this->buku->countAll(),
            'jumlahAnggota'  => $this->anggota->countAll(),
            'sedangDipinjam' => $sedangDipinjam,
            'pengunjung'     => $jumlahPengunjung,
            'tanggal'        => json_encode($tanggalArr),
            'total'          => json_encode($totalPinjamArr),
            'denda'          => json_encode($totalDendaArr),
        ];

        return view('dashboard/index', $data);
    }

    public function grafik()
    {
        // 🔐 Proteksi login
        if (!session()->get('isLoggedIn')) {
            return redirect()->to('/login');
        }

        $db = \Config\Database::connect();
        $seminggu = date('Y-m-d', strtotime('-6 days'));

        $grafikPinjam = $db
            ->table('peminjaman')
            ->select("DATE(tanggal_pinjam) as tgl, COUNT(id) as total")
            ->where('tanggal_pinjam >=', $seminggu)
            ->groupBy('DATE(tanggal_pinjam)')
            ->orderBy('tgl', 'ASC')
            ->get()
            ->getResultArray();

        $grafikDenda = $db
            ->table('peminjaman')
            ->select("DATE(tanggal_kembali) as tgl, SUM(denda) as total")
            ->where('tanggal_kembali >=', $seminggu)
            ->where('status', 'Dikembalikan')
            ->groupBy('DATE(tanggal_kembali)')
            ->orderBy('tgl', 'ASC')
            ->get()
            ->getResultArray();

        $tanggalArr = [];
        $totalPinjamArr = [];
        $totalDendaArr = [];

        for ($i = 6; $i >= 0; $i--) {
            $tgl = date('Y-m-d', strtotime("-$i days"));
            $tanggalArr[] = date('d-m-Y', strtotime($tgl));

            $foundPinjam = 0;
            foreach ($grafikPinjam as $g) {
                if ($g['tgl'] == $tgl) {
                    $foundPinjam = (int)$g['total'];
                    break;
                }
            }
            $totalPinjamArr[] = $foundPinjam;

            $foundDenda = 0;
            foreach ($grafikDenda as $g) {
                if ($g['tgl'] == $tgl) {
                    $foundDenda = (int)$g['total'];
                    break;
                }
            }
            $totalDendaArr[] = $foundDenda;
        }

        $data = [
            'title'   => 'Grafik Dashboard',
            'tanggal' => json_encode($tanggalArr),
            'total'   => json_encode($totalPinjamArr),
            'denda'   => json_encode($totalDendaArr),
        ];

        return view('dashboard/grafik', $data);
    }
}
