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

$id = intval($_POST['id'] ?? 0);
if (!$id) { echo json_encode(['success' => false, 'message' => 'Invalid ID']); exit(); }

$loan = fetchOne($conn, "SELECT status FROM loans WHERE id = ?", [$id], "i");
if (!$loan) { echo json_encode(['success' => false, 'message' => 'Loan not found']); exit(); }
if ($loan['status'] !== 'approved') {
    echo json_encode(['success' => false, 'message' => 'Only approved loans can be marked as released']);
    exit();
}

try {
    executeQuery($conn, "UPDATE loans SET status = 'released' WHERE id = ? AND status = 'approved'", [$id], "i");
    logActivity($conn, $_SESSION['user_id'], 'release_loan', "Released loan ID: $id");
    echo json_encode(['success' => true]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
