<?php
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/db.php';
require_login();
header('Content-Type: application/json');

$mysqli = db();
$action = $_GET['action'] ?? $_POST['action'] ?? 'list';

function cl_ok($d){ echo json_encode($d); exit; }
function cl_err($m,$c=400){ http_response_code($c); echo json_encode(['message'=>$m]); exit; }

if (!function_exists('json_response')) {
  function json_response($d,$c=200){ http_response_code($c); echo json_encode($d); exit; }
}

switch ($action) {
  case 'list': {
    $sql = 'SELECT id, institute_name, address, contact_person, contact_number, license_name, license_no, renew_date, expiry_date, remark
            FROM company_licenses
            ORDER BY expiry_date IS NULL ASC, expiry_date ASC, institute_name ASC';
    $res = $mysqli->query($sql);
    $rows = [];
    if ($res) while($r = $res->fetch_assoc()) $rows[] = $r;
    cl_ok(['data' => $rows]);
  } break;

  case 'get': {
    $id = (int)($_GET['id'] ?? 0); if(!$id) cl_err('Missing id');
    $stmt = $mysqli->prepare('SELECT id, institute_name, address, contact_person, contact_number, license_name, license_no, renew_date, expiry_date, remark FROM company_licenses WHERE id=?');
    $stmt->bind_param('i',$id); $stmt->execute(); $row = $stmt->get_result()->fetch_assoc();
    if(!$row) cl_err('Not found',404);
    cl_ok(['data'=>$row]);
  } break;

  case 'save': {
    if (!validate_csrf($_POST['csrf'] ?? '')) cl_err('Invalid CSRF',400);
    $id = (int)($_POST['id'] ?? 0);
    $institute_name = trim($_POST['institute_name'] ?? '');
    if ($institute_name==='') cl_err('Institute name required');
    $address = trim($_POST['address'] ?? '');
    $contact_person = trim($_POST['contact_person'] ?? '');
    $contact_number = trim($_POST['contact_number'] ?? '');
    $license_name = trim($_POST['license_name'] ?? '');
    $license_no = trim($_POST['license_no'] ?? '');
    $renew_date = trim($_POST['renew_date'] ?? '');
    $expiry_date = trim($_POST['expiry_date'] ?? '');
    $remark = trim($_POST['remark'] ?? '');

    $renew_date = $renew_date !== '' ? $renew_date : null;
    $expiry_date = $expiry_date !== '' ? $expiry_date : null;

    if ($id) {
      $stmt = $mysqli->prepare('UPDATE company_licenses SET institute_name=?, address=?, contact_person=?, contact_number=?, license_name=?, license_no=?, renew_date=?, expiry_date=?, remark=? WHERE id=?');
      $stmt->bind_param('sssssssssi',$institute_name,$address,$contact_person,$contact_number,$license_name,$license_no,$renew_date,$expiry_date,$remark,$id);
      if(!$stmt->execute()) cl_err($stmt->error,500);
      cl_ok(['message'=>'Updated','id'=>$id]);
    } else {
      $stmt = $mysqli->prepare('INSERT INTO company_licenses(institute_name,address,contact_person,contact_number,license_name,license_no,renew_date,expiry_date,remark) VALUES (?,?,?,?,?,?,?,?,?)');
      $stmt->bind_param('sssssssss',$institute_name,$address,$contact_person,$contact_number,$license_name,$license_no,$renew_date,$expiry_date,$remark);
      if(!$stmt->execute()) cl_err($stmt->error,500);
      cl_ok(['message'=>'Created','id'=>$mysqli->insert_id]);
    }
  } break;

  case 'delete': {
    if (!validate_csrf($_POST['csrf'] ?? '')) cl_err('Invalid CSRF',400);
    $id = (int)($_POST['id'] ?? 0); if(!$id) cl_err('Missing id');
    $stmt = $mysqli->prepare('DELETE FROM company_licenses WHERE id=?');
    $stmt->bind_param('i',$id);
    if(!$stmt->execute()) cl_err($stmt->error,500);
    cl_ok(['message'=>'Deleted']);
  } break;

  case 'expired_summary': {
    $today = date('Y-m-d');
    $stmt = $mysqli->prepare('SELECT COUNT(*) AS cnt FROM company_licenses WHERE expiry_date IS NOT NULL AND expiry_date < ?');
    $stmt->bind_param('s', $today);
    $stmt->execute();
    $res = $stmt->get_result();
    $row = $res ? $res->fetch_assoc() : ['cnt' => 0];
    $count = isset($row['cnt']) ? (int)$row['cnt'] : 0;
    cl_ok(['count' => $count]);
  } break;

  default:
    cl_err('Invalid action',400);
}
