<?php

namespace App\Controllers\PPDB;

use App\Controllers\BaseController;

class Admin extends BaseController
{
    public function index()
    {
        $db = \Config\Database::connect();

        $data = [
            'title' => 'Dashboard Permit',
            'total' => $db->table('hot_work_permits')->countAll(),
            'pending' => $db->table('hot_work_permits')->where('status', 3)->countAllResults(),
            'approved' => $db->table('hot_work_permits')->where('status', 1)->countAllResults(),
            'rejected' => $db->table('hot_work_permits')->where('status', 2)->countAllResults(),
        ];

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

    public function detail($id)
    {
        $model = new \App\Models\PPDBModel();
        $record = $model->find($id);

        if (!$record) {
            throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
        }

        return view('ppdb/admin/detail', [
            'record' => $record
        ]);
    }

    public function edit($id)
    {
        $model = new \App\Models\PpdbModel();
        $record = $model->find($id);

        if (!$record) {
            throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
        }

        return view('ppdb/admin/edit', [
            'record' => $record
        ]);
    }

    public function update($id)
    {
        $model = new \App\Models\PpdbModel();

        $data = $this->request->getPost();

        $model->update($id, [
            'name' => $data['name'],
            'nisn' => $data['nisn'],
            'birth_place' => $data['birth_place'],
            'birth_date' => $data['birth_date'],
            'gender' => $data['gender'],
            'phone' => $data['phone'],
            'address' => $data['address'],
            'father_name' => $data['father_name'],
            'father_job' => $data['father_job'],
            'mother_name' => $data['mother_name'],
            'mother_job' => $data['mother_job'],
            'school_origin' => $data['school_origin'],
            'school_address' => $data['school_address'],
        ]);

        session()->setFlashdata('success', 'Data berhasil diperbarui!');
        return redirect()->to(site_url('ppdb/admin/detail/' . $id));
    }

}
