<?php

namespace App\Controllers;

class Report extends BaseController
{
    public function index()
    {
        $session = session();
        $token = (string) $session->get('access_token');

        $page = max(1, (int) ($this->request->getGet('page') ?? 1));
        $perPage = (int) ($this->request->getGet('per_page') ?? 10);
        if ($perPage < 1) {
            $perPage = 10;
        } elseif ($perPage > 100) {
            $perPage = 100;
        }

        $startDate = trim((string) ($this->request->getGet('start_date') ?? ''));
        $endDate = trim((string) ($this->request->getGet('end_date') ?? ''));

        $apiBase = rtrim((string) (env('api.baseURL') ?? env('API_BASE_URL') ?? 'http://10.210.101.8/api'), '/');
        $url = $apiBase . '/visit/report';
        $payload = [
            'page' => $page,
        ];
        if ($startDate !== '') {
            $payload['start_date'] = $startDate;
        }
        if ($endDate !== '') {
            $payload['end_date'] = $endDate;
        }

        $items = [];
        $currentPage = $page;
        $total = 0;
        $message = null;
        $error = null;

        try {
            $client = service('curlrequest');
            $response = $client->post($url, [
                'headers' => [
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json',
                    'Authorization' => 'Bearer ' . $token,
                ],
                'body' => json_encode($payload),
                'http_errors' => false,
                'timeout' => 10,
            ]);
            $status = $response->getStatusCode();
            $body = (string) $response->getBody();
            $json = json_decode($body, true);

            if ($status === 200 && is_array($json)) {
                if (($json['status'] ?? '') === 'ok' || isset($json['data'])) {
                    $items = is_array($json['data'] ?? null) ? $json['data'] : [];
                    $currentPage = (int) ($json['current_page'] ?? $page);
                    $perPage = (int) ($json['per_page'] ?? $perPage);
                    $total = (int) ($json['total'] ?? 0);
                    $message = isset($json['message']) ? (string) $json['message'] : null;
                } else {
                    $error = isset($json['message']) ? (string) $json['message'] : 'Gagal memuat data report.';
                }
            } elseif ($status === 401) {
                return redirect()->to('/login');
            } else {
                $error = 'Gagal memuat data report. Kode: ' . $status;
            }
        } catch (\Throwable $e) {
            $error = 'Gagal menghubungi server report.';
        }

        $data = [
            'token' => $token,
            'token_expires_at' => $session->get('token_expires_at'),
            'user_email' => $session->get('user_email'),
            'items' => $items,
            'current_page' => $currentPage,
            'per_page' => $perPage,
            'total' => $total,
            'message' => $message,
            'error' => $error,
            'start_date' => $startDate,
            'end_date' => $endDate,
        ];
        return view('report', $data);
    }

    public function export()
    {
        $session = session();
        $token = (string) $session->get('access_token');

        $startDate = trim((string) ($this->request->getGet('start_date') ?? ''));
        $endDate = trim((string) ($this->request->getGet('end_date') ?? ''));

        $apiBase = rtrim((string) (env('api.baseURL') ?? env('API_BASE_URL') ?? 'http://10.210.101.8/api'), '/');
        $url = $apiBase . '/visit/report';

        $all = [];
        $page = 1;
        $maxPages = 1000;

        try {
            $client = service('curlrequest');
            while ($page <= $maxPages) {
                $payload = ['page' => $page];
                if ($startDate !== '') {
                    $payload['start_date'] = $startDate;
                }
                if ($endDate !== '') {
                    $payload['end_date'] = $endDate;
                }

                $response = $client->post($url, [
                    'headers' => [
                        'Accept' => 'application/json',
                        'Content-Type' => 'application/json',
                        'Authorization' => 'Bearer ' . $token,
                    ],
                    'body' => json_encode($payload),
                    'http_errors' => false,
                    'timeout' => 20,
                ]);

                $status = $response->getStatusCode();
                if ($status === 401) {
                    return redirect()->to('/login');
                }
                if ($status !== 200) {
                    break;
                }

                $json = json_decode((string) $response->getBody(), true);
                if (!is_array($json)) {
                    break;
                }

                $items = is_array($json['data'] ?? null) ? $json['data'] : [];
                if (empty($items)) {
                    break;
                }
                foreach ($items as $row) {
                    if (is_array($row)) {
                        $all[] = $row;
                    }
                }

                $currentPage = (int) ($json['current_page'] ?? $page);
                $perPage = (int) ($json['per_page'] ?? count($items));
                $total = (int) ($json['total'] ?? 0);
                $totalPages = $perPage > 0 ? (int) ceil($total / $perPage) : $page;
                if ($currentPage >= $totalPages) {
                    break;
                }
                $page++;
            }
        } catch (\Throwable $e) {
        }

        $fh = fopen('php://temp', 'r+');
        fwrite($fh, "\xEF\xBB\xBF");
        fputcsv($fh, ['No', 'Regis #', 'NIK', 'Nama', 'Tanggal', 'To', 'Room', 'Floor', 'Purpose', 'Image']);
        $i = 0;
        foreach ($all as $row) {
            fputcsv($fh, [
                ++$i,
                (string) ($row['regis_numbers'] ?? ''),
                (string) ($row['nik'] ?? ''),
                (string) ($row['name'] ?? ''),
                (string) ($row['regis_date'] ?? ''),
                (string) ($row['to'] ?? ''),
                (string) ($row['room'] ?? ''),
                (string) ($row['floor'] ?? ''),
                (string) ($row['purpose'] ?? ''),
                (string) ($row['image'] ?? ''),
            ]);
        }
        rewind($fh);
        $csv = stream_get_contents($fh);
        fclose($fh);

        $filename = 'report_' . date('Ymd_His') . '.csv';
        return $this->response
            ->setHeader('Content-Type', 'text/csv; charset=UTF-8')
            ->setHeader('Content-Disposition', 'attachment; filename="' . $filename . '"')
            ->setBody($csv);
    }
}
