<?php
// /edenrms/pages/approval_decide.php
// Approve/Reject an approval request. Applies effects for certain types (e.g., custom_plan).

declare(strict_types=1);
@date_default_timezone_set('Asia/Colombo');
header('Content-Type: application/json; charset=utf-8');

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

// ---------- DB bootstrap ----------
$mysqli = null;
if (is_file(__DIR__ . '/../includes/auth.php')) {
  require_once __DIR__ . '/../includes/auth.php';
  $db = function_exists('ec_db') ? ec_db() : null;
  if ($db instanceof mysqli) $mysqli = $db;
}
if (!$mysqli) { $mysqli = new mysqli('localhost','root','','edencamp_edencampus'); }
$mysqli->set_charset('utf8mb4');

// ---------- helpers ----------
function now(): string { return date('Y-m-d H:i:s'); }
function tableExists(mysqli $db, string $t): bool {
  $st = $db->prepare("SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?");
  $st->bind_param('s', $t); $st->execute(); $st->store_result();
  $ok = $st->num_rows > 0; $st->free_result(); $st->close(); return $ok;
}
function ensurePaymentSchedule(mysqli $db): string {
  if (tableExists($db,'payment_schedule')) return 'payment_schedule';
  if (tableExists($db,'installments'))     return 'installments';
  $db->query("CREATE TABLE IF NOT EXISTS payment_schedule (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    student_id INT UNSIGNED NOT NULL,
    installment_no INT UNSIGNED NOT NULL,
    course_fee DECIMAL(12,2) NOT NULL DEFAULT 0,
    reg_fee DECIMAL(12,2) NOT NULL DEFAULT 0,
    cert_fee DECIMAL(12,2) NOT NULL DEFAULT 0,
    due_date DATE NULL,
    status ENUM('PENDING','PAID','OVERDUE') NOT NULL DEFAULT 'PENDING',
    created_at DATETIME NOT NULL,
    INDEX (student_id), INDEX (installment_no), INDEX (status), INDEX (due_date)
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
  return 'payment_schedule';
}
function jerr($msg, $code=400){ http_response_code($code); echo json_encode(['ok'=>false,'message'=>$msg], JSON_UNESCAPED_UNICODE); exit; }

// ---------- auth ----------
session_start();
$role = strtolower((string)($_SESSION['user']['role'] ?? $_SESSION['role'] ?? ''));
$userId = (int)($_SESSION['user']['id'] ?? $_SESSION['id'] ?? 0);
if (!$userId) jerr('Not logged in', 401);
if (!in_array($role, ['admin','super_admin'], true)) jerr('Forbidden', 403);

// ---------- input ----------
$id  = (int)($_POST['id'] ?? $_GET['id'] ?? 0);
$act = strtolower((string)($_POST['action'] ?? $_GET['action'] ?? ''));
$note= trim((string)($_POST['note'] ?? $_GET['note'] ?? ''));
if ($id <= 0) jerr('Missing id');
if (!in_array($act, ['approve','reject'], true)) jerr('Invalid action');

// ---------- load approval ----------
$st = $mysqli->prepare("SELECT id,type,subtype,student_id,requested_by,payload_json,status FROM approvals WHERE id=?");
$st->bind_param('i', $id);
$st->execute(); $st->store_result();
if (!$st->num_rows) { $st->close(); jerr('Approval not found', 404); }
$st->bind_result($rid,$type,$sub,$student_id,$requested_by,$payload_json,$status);
$st->fetch(); $st->free_result(); $st->close();
if ($status !== 'PENDING') jerr('Already decided');

// ---------- decide ----------
if ($act === 'reject') {
  $st = $mysqli->prepare("UPDATE approvals SET status='REJECTED', decision_note=?, decided_by=?, decided_at=? WHERE id=?");
  $now = now(); $st->bind_param('sisi', $note, $userId, $now, $id);
  $st->execute(); $st->close();
  echo json_encode(['ok'=>true,'message'=>'Request rejected.']);
  exit;
}

// approve
$payload = json_decode((string)$payload_json, true) ?: [];
$mysqli->begin_transaction();
try {
  if ($type === 'custom_plan' || $type === 'custom_installment_plan') {
    $rows = $payload['rows'] ?? [];
    if (!is_array($rows) || !$rows) throw new RuntimeException('No rows in payload');
    $tbl = ensurePaymentSchedule($mysqli);

    // Optional: clear old schedule
    $st = $mysqli->prepare("DELETE FROM {$tbl} WHERE student_id=?");
    $st->bind_param('i', $student_id); $st->execute(); $st->close();

    if ($tbl === 'payment_schedule') {
      $st = $mysqli->prepare("INSERT INTO payment_schedule (student_id,installment_no,course_fee,reg_fee,cert_fee,due_date,status,created_at) VALUES (?,?,?,?,?,?, 'PENDING', ?)");
    } else {
      $st = $mysqli->prepare("INSERT INTO installments (student_id,installment_no,course_fee,reg_fee,cert_fee,due_date,status,created_at) VALUES (?,?,?,?,?,?, 'PENDING', ?)");
    }
    foreach ($rows as $r) {
      $n = (int)($r['n'] ?? $r['no'] ?? 0);
      $c = (float)($r['course_fee'] ?? 0);
      $g = (float)($r['reg_fee'] ?? 0);
      $t = (float)($r['cert_fee'] ?? 0);
      $d = trim((string)($r['due_date'] ?? ''));
      $d2 = $d !== '' ? $d : null;
      $created = now();
      $st->bind_param('iiiddss', $student_id, $n, $c, $g, $t, $d2, $created);
      $st->execute();
    }
    $st->close();
  }

  // mark approval as approved
  $st = $mysqli->prepare("UPDATE approvals SET status='APPROVED', decision_note=?, decided_by=?, decided_at=? WHERE id=?");
  $now = now(); $st->bind_param('sisi', $note, $userId, $now, $id);
  $st->execute(); $st->close();

  $mysqli->commit();
  echo json_encode(['ok'=>true,'message'=>'Request approved and applied.']);
} catch (Throwable $e) {
  $mysqli->rollback();
  jerr('Failed to apply: '.$e->getMessage(), 500);
}
