<?php
declare(strict_types=1);
@header('Content-Type: application/json; charset=utf-8');
if (session_status() !== PHP_SESSION_ACTIVE) session_start();

require_once __DIR__ . '/../includes/db.php';
$db = $conn ?? new mysqli('localhost','root','','edencamp_edencampus');
if ($db->connect_error) { http_response_code(500); echo json_encode(['ok'=>false,'message'=>'DB error']); exit; }
$db->set_charset('utf8mb4');

function tableExists(mysqli $db, string $t): bool {
  $st=$db->prepare("SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=? LIMIT 1");
  $st->bind_param('s',$t); $st->execute(); $ok=(bool)$st->get_result()->fetch_row(); $st->close(); return $ok;
}
function colExists(mysqli $db, string $t, string $c): bool {
  $st=$db->prepare("SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=? AND COLUMN_NAME=? LIMIT 1");
  $st->bind_param('ss',$t,$c); $st->execute(); $ok=(bool)$st->get_result()->fetch_row(); $st->close(); return $ok;
}

$student_id = (int)($_POST['student_id'] ?? 0);
$amount     = (float)($_POST['amount'] ?? 0);
$reason     = trim((string)($_POST['reason'] ?? ''));

if ($student_id <= 0 || $amount <= 0) { http_response_code(400); echo json_encode(['ok'=>false,'message'=>'Bad input']); exit; }

$role = strtolower((string)($_SESSION['role'] ?? $_SESSION['user']['role'] ?? 'staff'));
$is_admin = in_array($role, ['admin','super_admin','branch_admin'], true);
$actor_id = (int)($_SESSION['admin']['id'] ?? $_SESSION['user']['id'] ?? 0);

if (!tableExists($db,'studentss')) { http_response_code(500); echo json_encode(['ok'=>false,'message'=>'Tables missing']); exit; }

$chk = $db->prepare("SELECT id FROM studentss WHERE id=? LIMIT 1");
$chk->bind_param('i',$student_id); $chk->execute();
if (!$chk->get_result()->fetch_row()) { $chk->close(); http_response_code(404); echo json_encode(['ok'=>false,'message'=>'Student not found']); exit; }
$chk->close();

if (!$is_admin) {
  if (!tableExists($db,'approval_requests')) { http_response_code(500); echo json_encode(['ok'=>false,'message'=>'Approvals table missing']); exit; }
  $payload = json_encode(['amount_lkr'=>$amount,'reason'=>$reason], JSON_UNESCAPED_UNICODE);
  $st = $db->prepare("INSERT INTO approval_requests (type,status,student_id,requested_by,payload,requested_at)
                      VALUES ('discount','pending',?,?,?,NOW())");
  $st->bind_param('iis', $student_id, $actor_id, $payload);
  $ok = $st->execute(); $st->close();
  if (!$ok) { http_response_code(500); echo json_encode(['ok'=>false,'message'=>'Could not create request']); exit; }
  echo json_encode(['ok'=>true,'pending'=>true,'message'=>'Discount request sent for approval.']); exit;
}

if (!tableExists($db,'student_fee_plans')) { http_response_code(500); echo json_encode(['ok'=>false,'message'=>'student_fee_plans missing']); exit; }

$targetCol = null;
foreach (['manual_discount_lkr','plan_discount_lkr','discount_lkr'] as $c) {
  if (colExists($db,'student_fee_plans',$c)) { $targetCol = $c; break; }
}
if ($targetCol === null) { http_response_code(500); echo json_encode(['ok'=>false,'message'=>'No discount column found in student_fee_plans']); exit; }

$db->begin_transaction();
try {
  $sfpId = null;
  $st = $db->prepare("SELECT id FROM student_fee_plans WHERE student_id=? ORDER BY id DESC LIMIT 1");
  $st->bind_param('i',$student_id); $st->execute();
  $row = $st->get_result()->fetch_assoc(); $st->close();
  if ($row) $sfpId = (int)$row['id'];

  if ($sfpId === null) {
    $st = $db->prepare("INSERT INTO student_fee_plans (student_id, {$targetCol}) VALUES (?, ?)");
    $st->bind_param('id', $student_id, $amount);
    if (!$st->execute()) throw new Exception('Failed to create fee plan');
    $sfpId = (int)$db->insert_id; $st->close();
  } else {
    $sql = "UPDATE student_fee_plans SET {$targetCol}=COALESCE({$targetCol},0)+? WHERE id=?";
    $st  = $db->prepare($sql); $st->bind_param('di', $amount, $sfpId);
    if (!$st->execute()) throw new Exception('Failed to apply discount');
    $st->close();
  }

  if (tableExists($db,'approval_requests')) {
    $payload = json_encode(['amount_lkr'=>$amount,'reason'=>$reason], JSON_UNESCAPED_UNICODE);
    $st = $db->prepare("INSERT INTO approval_requests
                        (type,status,student_id,requested_by,approved_by,decided_by,decided_at,payload,requested_at)
                        VALUES ('discount','approved',?,?,?,?,NOW(),?,NOW())");
    $st->bind_param('iiiis', $student_id, $actor_id, $actor_id, $actor_id, $payload);
    $st->execute(); $st->close();
  }

  $db->commit();
  echo json_encode(['ok'=>true,'applied'=>true,'message'=>'Discount applied.']); exit;
} catch (Throwable $e) {
  $db->rollback();
  http_response_code(500);
  echo json_encode(['ok'=>false,'message'=>$e->getMessage()]); exit;
}
