<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\Common_model;

class Report extends BaseController
{
    protected $common;
    protected $attendanceTable = 'attendance';
    protected $usersTable = 'tbl_users';

    public function __construct()
    {
        $this->common = new Common_model();
    }

    /* ================= ATTENDANCE REPORT LIST ================= */
    public function index()
    {
        // 🔐 Admin check
        if (session()->get('role') !== 'Admin') {
            return redirect()->to('/home')->with('error', 'Unauthorized access');
        }

        $from = $this->request->getGet('from_date');
        $to   = $this->request->getGet('to_date');

        $where = [];

        if (!empty($from) && !empty($to)) {
            $where = [
                'attendance.attendance_date >=' => $from,
                'attendance.attendance_date <=' => $to
            ];
        }

        /*
         | ------------------------------------------------------------
         | Since Users controller uses getData(),
         | we first fetch attendance records,
         | then map user details manually.
         | ------------------------------------------------------------
         */

        $attendanceRecords = $this->common->getData(
            $this->attendanceTable,
            'id,user_id,attendance_date,punch_in_time,punch_out_time,work_mode',
            $where,
            [],
            'attendance_date DESC'
        );

        $records = [];

        if (!empty($attendanceRecords)) {
            foreach ($attendanceRecords as $row) {

                // Fetch user details
                $user = $this->common->getData(
                    $this->usersTable,
                    'name,username',
                    ['id' => $row['user_id']]
                );

                $records[] = [
                    'name'            => $user[0]['name'] ?? '',
                    'username'        => $user[0]['username'] ?? '',
                    'attendance_date' => $row['attendance_date'],
                    'punch_in_time'   => $row['punch_in_time'],
                    'punch_out_time'  => $row['punch_out_time'],
                    'work_mode'       => $row['work_mode']
                ];
            }
        }

        $data['records'] = $records;

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

    /* ================= EXPORT ATTENDANCE CSV ================= */
    public function exportCsv()
    {
        if (session()->get('role') !== 'Admin') {
            return redirect()->to('/home')->with('error', 'Unauthorized access');
        }

        $from = $this->request->getGet('from_date');
        $to   = $this->request->getGet('to_date');

        $where = [];

        if (!empty($from) && !empty($to)) {
            $where = [
                'attendance_date >=' => $from,
                'attendance_date <=' => $to
            ];
        }

        $attendanceRecords = $this->common->getData(
            $this->attendanceTable,
            'user_id,attendance_date,punch_in_time,punch_out_time,work_mode',
            $where,
            [],
            'attendance_date DESC'
        );

        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="attendance_report.csv"');

        $file = fopen('php://output', 'w');
        fputcsv($file, ['Name','Username','Date','Punch In','Punch Out','Work Mode']);

        foreach ($attendanceRecords as $row) {

            $user = $this->common->getData(
                $this->usersTable,
                'name,username',
                ['id' => $row['user_id']]
            );

            fputcsv($file, [
                $user[0]['name'] ?? '',
                $user[0]['username'] ?? '',
                $row['attendance_date'],
                $row['punch_in_time'],
                $row['punch_out_time'],
                $row['work_mode']
            ]);
        }

        fclose($file);
        exit;
    }
}
