<?php

namespace App\Controllers;

use Core\Controller;
use Core\Database;
use PDO;

class PresenKegiatanController extends Controller
{
    private $db;

    public function __construct()
    {
        $this->db = Database::getConnection();
    }

    public function index()
    {
        // ambil kegiatan aktif
        $stmt = $this->db->prepare("SELECT * FROM tb_jenis_kegiatan WHERE status = 'Aktif' LIMIT 1");
        $stmt->execute();
        $kegiatan = $stmt->fetch(PDO::FETCH_ASSOC);

        // ambil daftar presensi untuk kegiatan aktif
        $presensi = [];
        if ($kegiatan) {
            $stmt2 = $this->db->prepare("
                SELECT p.username, p.nama_peserta, k.nama_kegiatan, k.tanggal, p.waktu_presensi
                FROM tb_presensi_kegiatan p
                INNER JOIN tb_jenis_kegiatan k ON p.id_jenis_kegiatan = k.id_jenis_kegiatan
                WHERE p.id_jenis_kegiatan = ?
                ORDER BY p.waktu_presensi DESC
            ");
            $stmt2->execute([$kegiatan['id_jenis_kegiatan']]);
            $presensi = $stmt2->fetchAll(PDO::FETCH_ASSOC);
        }

        require_once __DIR__ . '/../Views/pegawai/presen_kegiatan.php';
    }

    // manual submit (nisn input)
    public function store()
    {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $nisn = trim($_POST['nisn']);

            // cek kegiatan aktif
            $stmt = $this->db->prepare("SELECT * FROM tb_jenis_kegiatan WHERE status = 'Aktif' LIMIT 1");
            $stmt->execute();
            $kegiatan = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$kegiatan) {
                $_SESSION['error'] = "Tidak ada kegiatan aktif.";
                header("Location: /dashboard/pegawai-presen-kegiatan");
                exit;
            }

            // cek peserta dari tb_pmb
            $stmt2 = $this->db->prepare("SELECT * FROM tb_pmb WHERE nisn = ?");
            $stmt2->execute([$nisn]);
            $peserta = $stmt2->fetch(PDO::FETCH_ASSOC);

            if (!$peserta) {
                $_SESSION['error'] = "NISN tidak ditemukan di data PMB.";
                header("Location: /dashboard/pegawai-presen-kegiatan");
                exit;
            }

            $username = $peserta['nisn'];
            $nama_peserta = $peserta['nama_camaba'];

            try {
                $stmt3 = $this->db->prepare("
                    INSERT INTO tb_presensi_kegiatan (username, nama_peserta, id_jenis_kegiatan) 
                    VALUES (?, ?, ?)
                ");
                $stmt3->execute([$username, $nama_peserta, $kegiatan['id_jenis_kegiatan']]);
                $_SESSION['success'] = "Presensi berhasil untuk $nama_peserta.";
            } catch (\PDOException $e) {
                $_SESSION['error'] = "Peserta sudah presensi di kegiatan ini.";
            }

            header("Location: /dashboard/pegawai-presen-kegiatan");
            exit;
        }
    }

    // API untuk scan realtime (dipanggil via AJAX dari kamera)
    public function scan()
    {
        header('Content-Type: application/json');

        $nisn = trim($_POST['nisn']);

        // cek kegiatan aktif
        $stmt = $this->db->prepare("SELECT * FROM tb_jenis_kegiatan WHERE status = 'Aktif' LIMIT 1");
        $stmt->execute();
        $kegiatan = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$kegiatan) {
            echo json_encode(['status' => 'error', 'message' => 'Tidak ada kegiatan aktif']);
            return;
        }

        // cek peserta
        $stmt2 = $this->db->prepare("SELECT * FROM tb_pmb WHERE nisn = ?");
        $stmt2->execute([$nisn]);
        $peserta = $stmt2->fetch(PDO::FETCH_ASSOC);

        if (!$peserta) {
            echo json_encode(['status' => 'error', 'message' => 'NISN tidak ditemukan']);
            return;
        }

        $username = $peserta['nisn'];
        $nama_peserta = $peserta['nama_camaba'];

        try {
            $stmt3 = $this->db->prepare("
                INSERT INTO tb_presensi_kegiatan (username, nama_peserta, id_jenis_kegiatan) 
                VALUES (?, ?, ?)
            ");
            $stmt3->execute([$username, $nama_peserta, $kegiatan['id_jenis_kegiatan']]);
            echo json_encode(['status' => 'success', 'message' => "Presensi berhasil untuk $nama_peserta"]);
        } catch (\PDOException $e) {
            echo json_encode(['status' => 'error', 'message' => 'Peserta sudah presensi di kegiatan ini']);
        }
    }
}
