<?php

namespace App\Controllers;

use Core\Controller;
use App\Models\DataPMB;

class DataPMBController extends Controller
{
	
    protected $model;

    public function __construct()
    {
		if (!isset($_SESSION['user'])) {
			header('Location: /login');
			exit;
		} 
        $this->model = new DataPMB();
    }

    public function index()
    {
		
		
		try {
			$db = \Core\Database::getConnection();
			$db->query('SELECT 1'); // Cek koneksi
		} catch (\PDOException $e) {
			die("Test koneksi gagal: " . $e->getMessage());
			}


        // Tangani POST update status WA
        if (isset($_POST['update_wa'])) {
            $id_pmb = $_POST['id_pmb'];
            $updated = $this->model->updateStatusWA($id_pmb);

            if ($updated) {
                $_SESSION['pesan'] = "Status WA berhasil diperbarui!";
                $_SESSION['status_alert'] = "success";
            } else {
                $_SESSION['pesan'] = "Gagal memperbarui status.";
                $_SESSION['status_alert'] = "danger";
            }
            header("Location: /dashboard/admin-data_pmb");
            exit;
        }

        // Tangani POST verifikasi status
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['idPmb'], $_POST['statusBaru'])) {
            $id = $_POST['idPmb'];
            $status = $_POST['statusBaru'];

            $updated = $this->model->updateStatus($id, $status);

            if ($updated) {
                $_SESSION['pesan'] = "Status berhasil diperbarui!";
                $_SESSION['status_alert'] = "success";
            } else {
                $_SESSION['pesan'] = "Gagal memperbarui status. Silakan coba lagi.";
                $_SESSION['status_alert'] = "danger";
            }
            header("Location: /dashboard/admin-data_pmb");
            exit;
        }

		// Tangani update status ajax (POST dengan id dan status)
		if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['id'], $_POST['status']) && isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
			$id = $_POST['id'];
			$status = $_POST['status'];

			$updated = $this->model->updateStatus($id, $status);

			header('Content-Type: application/json');
			echo json_encode(['result' => $updated ? 'success' : 'error']);
			exit;
		}

        // Ambil parameter pencarian dan paging
        $search = $_GET['search'] ?? '';
        $page = isset($_GET['page_no']) && is_numeric($_GET['page_no']) ? (int)$_GET['page_no'] : 1;
        $limit = 25;
        $offset = ($page - 1) * $limit;

        // Ambil data PMB dan total halaman
        $totalRows = $this->model->countData($search);
        $totalPages = ceil($totalRows / $limit);
        $data = $this->model->getData($search, $limit, $offset);
        $tahunOptions = $this->model->getDistinctTahunMasuk();

        // Load view dengan data
		$this->view('admin/admin_data_pmb', [
			'data_pmb' => $data,
			'search' => $search,
			'page_no' => $page,
			'totalPages' => $totalPages,
			'tahun_list' => $this->model->getDistinctTahunMasuk(),
			'offset' => $offset,
			'pesan' => $_SESSION['pesan'] ?? '',
			'status_alert' => $_SESSION['status_alert'] ?? '',
		]);
		
        // Reset session pesan
        unset($_SESSION['pesan'], $_SESSION['status_alert']);
    }
}
