<?php
namespace App\Controllers;
use CodeIgniter\API\ResponseTrait;
use App\Controllers\BaseController;

class ApiValidateController extends BaseController
{
    use ResponseTrait;

    /**
     * GET /api/requests/unvalidated?date1=...&date2=...
     * Fetch requests that have not been validated yet by the current user
     */
    public function unvalidated()
    {
        $date1 = $this->request->getGet("date1");
        $date2 = $this->request->getGet("date2");
        $userid = session()->get("userid");

        if (empty($date1) || empty($date2)) {
            return $this->response->setJSON([
                "status" => "error",
                "message" => "Date range required",
            ]);
        }

        $db = \Config\Database::connect();

        $sql = "SELECT d.*, r.ISVAL1, r.ISVAL2, r.VAL1USER, r.VAL2USER
                FROM GDC_CMOD.dbo.V_DASHBOARD_DEV d
                LEFT JOIN GDC_CMOD.dbo.CM_REQUESTS r ON r.ACCESSNUMBER = d.SP_ACCESSNUMBER
                WHERE d.STATS = 'Fin'
                AND d.TESTS LIKE '%[A-Za-z]%'
                -- Exclude fully validated (both ISVAL1 and ISVAL2 are 1)
                AND (COALESCE(r.ISVAL1, 0) = 0 OR COALESCE(r.ISVAL2, 0) = 0)
                -- Exclude requests already validated by current user
                AND (r.VAL1USER != '$userid' OR r.VAL1USER IS NULL)
                AND (r.VAL2USER != '$userid' OR r.VAL2USER IS NULL)
                and d.COLLECTIONDATE between '$date1 00:00' and '$date2 23:59'
                and d.ODR_DDATE between '$date1 00:00' and '$date2 23:59'
                ORDER BY d.REQDATE DESC";

        $result = $db->query($sql)->getResultArray();

        // Format dates
        foreach ($result as &$row) {
            $row["REQDATE"] = date("Y-m-d H:i", strtotime($row["REQDATE"]));
            $row["ODR_DDATE"] = date("Y-m-d H:i", strtotime($row["ODR_DDATE"]));
            $row["COLLECTIONDATE"] = date(
                "Y-m-d H:i",
                strtotime($row["COLLECTIONDATE"]),
            );
        }

        return $this->response->setJSON([
            "status" => "success",
            "data" => $result,
        ]);
    }
}
