<?php
header('Content-Type: application/json');
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/admin_auth.php';

if (!isAdminLoggedIn()) {
  echo json_encode(['success' => false, 'error' => 'Not authorized']);
  exit;
}

try {
  $pdo = getDB();
  $input = json_decode(file_get_contents('php://input'), true) ?: [];
  $id = isset($input['id']) ? intval($input['id']) : 0;
  $action = isset($input['action']) ? trim($input['action']) : '';
  if ($id <= 0 || $action === '') {
    echo json_encode(['success' => false, 'error' => 'Invalid payload']);
    exit;
  }

  $allowed = ['approve','reject','activate','close'];
  if (!in_array($action, $allowed, true)) {
    echo json_encode(['success' => false, 'error' => 'Invalid action']);
    exit;
  }

  $adminId = getAdminId();
  $now = date('Y-m-d H:i:s');

  switch ($action) {
    case 'approve':
      $stmt = $pdo->prepare("UPDATE loans SET status='approved', approved_by=:aid, approved_at=:ts WHERE id=:id");
      $stmt->execute([':aid'=>$adminId, ':ts'=>$now, ':id'=>$id]);
      break;
    case 'reject':
      $stmt = $pdo->prepare("UPDATE loans SET status='rejected', approved_by=:aid, approved_at=:ts WHERE id=:id");
      $stmt->execute([':aid'=>$adminId, ':ts'=>$now, ':id'=>$id]);
      break;
    case 'activate':
      // When activating, set next due date ~30 days from now
      $nextDue = date('Y-m-d', strtotime('+30 days'));
      $stmt = $pdo->prepare("UPDATE loans SET status='active', next_due_date=:due, approved_by=:aid, approved_at=:ts WHERE id=:id");
      $stmt->execute([':due'=>$nextDue, ':aid'=>$adminId, ':ts'=>$now, ':id'=>$id]);
      break;
    case 'close':
      $stmt = $pdo->prepare("UPDATE loans SET status='closed' WHERE id=:id");
      $stmt->execute([':id'=>$id]);
      break;
  }

  echo json_encode(['success' => true]);
} catch (Throwable $e) {
  echo json_encode(['success' => false, 'error' => 'Server error']);
}
