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

class RequestsController extends BaseController
{
  use ResponseTrait;

  public function index()
  {
    $db = \Config\Database::connect();
    $date1 = $this->request->getGet('date1');
    $date2 = $this->request->getGet('date2');
    $userroleid = session()->get('userroleid');

    // Only allow Lab role (role 2)
    if ($userroleid == 2) {
      $sql = "SELECT d.*, r.REPORT_LANG, r.ISPDF from GDC_CMOD.dbo.V_DASHBOARD_DEV d
        LEFT JOIN GDC_CMOD.dbo.CM_REQUESTS r ON r.ACCESSNUMBER=d.SP_ACCESSNUMBER
        where d.COLLECTIONDATE between '$date1 00:00' and '$date2 23:59'
        and d.ODR_DDATE between '$date1 00:00' and '$date2 23:59'
        and (d.TESTS IS NOT NULL AND d.TESTS like '%[A-Za-z]%')";
    } else {
      $sql = "SELECT d.*, r.REPORT_LANG, r.ISPDF from GDC_CMOD.dbo.V_DASHBOARD_DEV d
        LEFT JOIN GDC_CMOD.dbo.CM_REQUESTS r ON r.ACCESSNUMBER=d.SP_ACCESSNUMBER
        where d.COLLECTIONDATE between '$date1 00:00' and '$date2 23:59'
        and d.ODR_DDATE between '$date1 00:00' and '$date2 23:59'";
    }

    $rows = $db->query($sql)->getResultArray();
    foreach ($rows as &$row) {
      $row['COLLECTIONDATE'] = date('Y-m-d H:i', strtotime($row['COLLECTIONDATE']));
      $row['ODR_DDATE'] = date('Y-m-d H:i', strtotime($row['ODR_DDATE']));
      $row['REQDATE'] = date('Y-m-d H:i', strtotime($row['REQDATE']));
    }
    $data['data'] = $rows;
    return $this->response->setJSON($data);
  }


  public function show($accessnumber)
  {
    $db = \Config\Database::connect();
    $data['accessnumber'] = $accessnumber;
    $sql = "SELECT d.STATS, r.* FROM GDC_CMOD.dbo.V_DASHBOARD_DEV d
      left join GDC_CMOD.dbo.CM_REQUESTS r ON r.ACCESSNUMBER=d.SP_ACCESSNUMBER
      WHERE d.SP_ACCESSNUMBER='$accessnumber'";
    $result = $db
      ->query($sql)
      ->getResultArray();
    $data['val1'] = $result[0]['ISVAL1'];
    $data['val1user'] = $result[0]['VAL1USER'];
    $data['val2'] = $result[0]['ISVAL2'];
    $data['val2user'] = $result[0]['VAL2USER'];
    return view('admin/modal_request', $data);
  }

  public function showUnval($accessnumber)
  {
    $data['accessnumber'] = $accessnumber;
    return view('admin/modal_unvalidate', $data);
  }

  public function unval($accessnumber)
  {
    $input = $this->request->getJSON(true);
    $userid = session('userid');
    $comment = $input['comment'];
    $db = \Config\Database::connect();
    $sql = "update GDC_CMOD.dbo.CM_REQUESTS set ISVAL1=null, VAL1USER=null, VAL1DATE=null, ISVAL2=null, VAL2USER=null, VAL2DATE=null,
      ISPENDING=1, PENDINGTEXT='$comment', PENDINGUSER='$userid', PENDINGDATE=GETDATE() where ACCESSNUMBER='$accessnumber'";
    $db->query($sql);
    
    $logAudit = "INSERT INTO GDC_CMOD.dbo.AUDIT_EVENTS (ACCESSNUMBER, EVENT_TYPE, USERID, EVENT_AT, REASON)
                 VALUES (?, 'UNVAL', ?, GETDATE(), ?)";
    $db->query($logAudit, [$accessnumber, $userid, $comment]);
    
    $data = ['status' => 'success', 'message' => 'Data updated successfully', 'data' => "$accessnumber"];

    return $this->response->setJSON($data);
  }

  public function val($accessnumber)
  {
    $input = $this->request->getJSON(true);
    // Securely get userid from session
    $userid = session('userid');
    $db = \Config\Database::connect();
    $sql = "select * from GDC_CMOD.dbo.CM_REQUESTS where ACCESSNUMBER='$accessnumber'";
    $result = $db->query($sql)->getResultArray();
    if (!isset($result[0])) {
      $sql = "insert into GDC_CMOD.dbo.CM_REQUESTS(ACCESSNUMBER, ISVAL1, VAL1USER, VAL1DATE) VALUES ('$accessnumber', 1, '$userid', GETDATE())";
      $db->query($sql);
      
      $logAudit = "INSERT INTO GDC_CMOD.dbo.AUDIT_EVENTS (ACCESSNUMBER, EVENT_TYPE, USERID, EVENT_AT) VALUES (?, 'VAL1', ?, GETDATE())";
      $db->query($logAudit, [$accessnumber, $userid]);
      
      $data['val'] = 1;
      $data['userid'] = $userid;
    } else {
      $row = $result[0];
      $isval1 = $row['ISVAL1'];
      $isval2 = $row['ISVAL2'];
      $val1user = $row['VAL1USER'];
      if ($isval1 == 1) {
        if ($isval2 == 1) {
          return $this->response->setJSON(['message' => 'validation done, not updating anything']);
        } else {
          if ($val1user != $userid) {
            $sql = "update GDC_CMOD.dbo.CM_REQUESTS set ISVAL2=1, VAL2USER='$userid', VAL2DATE=GETDATE() where ACCESSNUMBER='$accessnumber'";
            
            $logAudit = "INSERT INTO GDC_CMOD.dbo.AUDIT_EVENTS (ACCESSNUMBER, EVENT_TYPE, USERID, EVENT_AT) VALUES (?, 'VAL2', ?, GETDATE())";
            $db->query($logAudit, [$accessnumber, $userid]);
            
            $data['val'] = 2;
            $data['userid'] = $userid;
          } else {
            $this->response->setStatusCode(500);
            return $this->response->setJSON(['message' => 'user already validate this request']);
          }
        }
      } else {
        $sql = "update GDC_CMOD.dbo.CM_REQUESTS set ISVAL1=1, VAL1USER='$userid', VAL1DATE=GETDATE() where ACCESSNUMBER='$accessnumber'";
        
        $logAudit = "INSERT INTO GDC_CMOD.dbo.AUDIT_EVENTS (ACCESSNUMBER, EVENT_TYPE, USERID, EVENT_AT) VALUES (?, 'VAL1', ?, GETDATE())";
        $db->query($logAudit, [$accessnumber, $userid]);
        
        $data['val'] = 1;
        $data['userid'] = $userid;
      }
      $db->query($sql);
    }

    return $this->response->setJSON($data);
  }

    public function setEngLanguage($accessnumber)
    {
        $userid = session('userid');
        $db = \Config\Database::connect();

        // Set REPORT_LANG to 1 (English)
        $sql = "UPDATE GDC_CMOD.dbo.CM_REQUESTS SET REPORT_LANG=1 WHERE ACCESSNUMBER='$accessnumber'";
        $db->query($sql);

        // Log the action
        $logAudit = "INSERT INTO GDC_CMOD.dbo.AUDIT_EVENTS (ACCESSNUMBER, EVENT_TYPE, USERID, EVENT_AT) VALUES (?, 'SET_ENG', ?, GETDATE())";
        $db->query($logAudit, [$accessnumber, $userid]);

        // Auto-generate English PDF
        $pdfResult = $this->generateEngPdf($accessnumber);

        return $this->response->setJSON([
            'status' => 'success',
            'message' => 'English result created',
            'pdf' => $pdfResult
        ]);
    }

    private function generateEngPdf(string $accessnumber): array
    {
        $db = \Config\Database::connect();
        $reportHelper = new \App\Libraries\ReportHelper($db);

        $data = $reportHelper->getReportData($accessnumber, 1);
        $data['eng'] = 1;
        $data['accessnumber'] = $accessnumber;
        $data['ispdf'] = 1;

        $html = view('report/template', $data);
        $filename = $accessnumber . '_eng.pdf';

        // Post to spooler
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'http://glenlis:3000/api/pdf/generate');
        curl_setopt($ch, CURLOPT_POST, 1);

$payload = [
            'html' => $html,
            'filename' => $filename,
            'accessnumber' => $accessnumber
        ];

        if (!empty($data['collectionDate'])) {
            $payload['collectionDate'] = $data['collectionDate'];
        }

        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json'
        ]);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($httpCode !== 200) {
            log_message('error', "PDF spooler returned HTTP $httpCode for ENG result $accessnumber");
            return ['success' => false, 'error' => 'Failed to queue PDF generation'];
        }

        $responseData = json_decode($response, true);

        // Log PDF generation
        $stepType = 'ENG_PDF';
        $stepStatus = 'English';
        $sqlLog = "INSERT INTO GDC_CMOD.dbo.AUDIT_REQUESTS(ACCESSNUMBER, STEPDATE, STEPTYPE, STEPSTATUS)
                   VALUES (?, GETDATE(), ?, ?)";
        $db->query($sqlLog, [(string)$accessnumber, $stepType, $stepStatus]);

        return [
            'success' => true,
            'jobId' => $responseData['jobId'] ?? null,
            'message' => 'English PDF queued for generation'
        ];
    }

    public function setPdfFlag(string $accessnumber): \CodeIgniter\HTTP\ResponseInterface
    {
        $db = \Config\Database::connect();
        
        $sql = "UPDATE GDC_CMOD.dbo.CM_REQUESTS SET ISPDF = 1 WHERE ACCESSNUMBER = ?";
        $db->query($sql, [$accessnumber]);
        
        $logAudit = "INSERT INTO GDC_CMOD.dbo.AUDIT_EVENTS (ACCESSNUMBER, EVENT_TYPE, USERID, EVENT_AT) VALUES (?, 'PDF_FLAG', 'SYSTEM', GETDATE())";
        $db->query($logAudit, [$accessnumber]);
        
        return $this->response->setJSON([
            'status' => 'success',
            'accessnumber' => $accessnumber
        ]);
    }
}
