<?php
session_start();
require_once '../../config/database.php';
require_once '../../customer/includes/notification_functions.php'; // Assuming notification functions are in the customer includes

// Check if admin is logged in
if (!isset($_SESSION['admin_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

$database = new Database();
$db = $database->getConnection();
$action = $_POST['action'] ?? '';

if ($action == 'approve') {
    $loan_id = $_POST['loan_id'];
    $note = $_POST['note'] ?? 'Loan approved.';

    try {
        $db->beginTransaction();

        // Update loan status
        $stmt = $db->prepare("UPDATE loans SET status = 'active', start_date = CURDATE(), end_date = DATE_ADD(CURDATE(), INTERVAL term_months MONTH) WHERE id = ? AND status = 'pending'");
        $stmt->execute([$loan_id]);

        // Get loan and user details
        $stmt = $db->prepare("SELECT user_id, total_amount FROM loans WHERE id = ?");
        $stmt->execute([$loan_id]);
        $loan = $stmt->fetch(PDO::FETCH_ASSOC);

        // Credit the loan amount to the user's account
        $stmt = $db->prepare("UPDATE users SET balance = balance + ? WHERE id = ?");
        $stmt->execute([$loan['total_amount'], $loan['user_id']]);

        // Create a transaction record
        $stmt = $db->prepare("INSERT INTO transactions (user_id, type, amount, status, description, transaction_type) VALUES (?, 'credit', ?, 'completed', 'Loan Disbursed', 'loan')");
        $stmt->execute([$loan['user_id'], $loan['total_amount']]);

        // Add a note
        $stmt = $db->prepare("INSERT INTO loan_notes (loan_id, admin_id, note) VALUES (?, ?, ?)");
        $stmt->execute([$loan_id, $_SESSION['admin_id'], $note]);

        // Create a notification for the user
        createNotification($db, $loan['user_id'], 'loan_status', 'Loan Approved', 'Your loan application has been approved and the amount has been credited to your account.', 'loans.php');

        $db->commit();
        echo json_encode(['success' => true]);
    } catch (Exception $e) {
        $db->rollBack();
        echo json_encode(['success' => false, 'message' => 'An error occurred: ' . $e->getMessage()]);
    }
} elseif ($action == 'reject') {
    $loan_id = $_POST['loan_id'];
    $reason = $_POST['reason'];

    try {
        // Update loan status
        $stmt = $db->prepare("UPDATE loans SET status = 'rejected' WHERE id = ? AND status = 'pending'");
        $stmt->execute([$loan_id]);

        // Add a note with the rejection reason
        $stmt = $db->prepare("INSERT INTO loan_notes (loan_id, admin_id, note) VALUES (?, ?, ?)");
        $stmt->execute([$loan_id, $_SESSION['admin_id'], 'Loan rejected. Reason: ' . $reason]);
        
        // Get user ID for notification
        $stmt = $db->prepare("SELECT user_id FROM loans WHERE id = ?");
        $stmt->execute([$loan_id]);
        $user_id = $stmt->fetchColumn();

        // Create a notification for the user
        createNotification($db, $user_id, 'loan_status', 'Loan Application Update', 'Your loan application has been rejected. Reason: ' . $reason, 'loans.php');

        echo json_encode(['success' => true]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => 'An error occurred: ' . $e->getMessage()]);
    }
} elseif ($action == 'add_payment') {
    $loan_id = $_POST['loan_id'];
    $amount = $_POST['amount'];
    $payment_date = $_POST['payment_date'];
    $payment_method = $_POST['payment_method'];
    $transaction_reference = $_POST['transaction_reference'] ?? '';

    try {
        $db->beginTransaction();

        // Get loan details
        $stmt = $db->prepare("SELECT user_id, total_amount, amount_paid FROM loans WHERE id = ?");
        $stmt->execute([$loan_id]);
        $loan = $stmt->fetch(PDO::FETCH_ASSOC);

        // Calculate new amount paid
        $new_amount_paid = $loan['amount_paid'] + $amount;
        
        // Update loan amount_paid
        $stmt = $db->prepare("UPDATE loans SET amount_paid = ?, last_payment_date = ? WHERE id = ?");
        $stmt->execute([$new_amount_paid, $payment_date, $loan_id]);

        // Check if loan is fully paid
        if ($new_amount_paid >= $loan['total_amount']) {
            $stmt = $db->prepare("UPDATE loans SET status = 'paid_off' WHERE id = ?");
            $stmt->execute([$loan_id]);
        }

        // Record payment
        $stmt = $db->prepare("INSERT INTO loan_payments (loan_id, amount, payment_date, payment_method, transaction_reference) VALUES (?, ?, ?, ?, ?)");
        $stmt->execute([$loan_id, $amount, $payment_date, $payment_method, $transaction_reference]);

        // Add a note
        $stmt = $db->prepare("INSERT INTO loan_notes (loan_id, admin_id, note) VALUES (?, ?, ?)");
        $stmt->execute([$loan_id, $_SESSION['admin_id'], "Payment of $" . number_format($amount, 2) . " recorded via $payment_method."]);

        // Create a notification for the user
        createNotification($db, $loan['user_id'], 'loan_payment', 'Loan Payment Recorded', 'A payment of $' . number_format($amount, 2) . ' has been recorded for your loan.', 'loans.php');

        $db->commit();
        echo json_encode(['success' => true]);
    } catch (Exception $e) {
        $db->rollBack();
        echo json_encode(['success' => false, 'message' => 'An error occurred: ' . $e->getMessage()]);
    }
} elseif ($action == 'add_note') {
    $loan_id = $_POST['loan_id'];
    $note = $_POST['note'];

    try {
        $stmt = $db->prepare("INSERT INTO loan_notes (loan_id, admin_id, note) VALUES (?, ?, ?)");
        $stmt->execute([$loan_id, $_SESSION['admin_id'], $note]);
        echo json_encode(['success' => true]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => 'An error occurred: ' . $e->getMessage()]);
    }
} elseif ($action == 'upload_document') {
    $loan_id = $_POST['loan_id'];
    $document_name = $_POST['document_name'];
    $document_type = $_POST['document_type'];
    
    // Handle file upload
    if (isset($_FILES['document_file']) && $_FILES['document_file']['error'] == 0) {
        $allowed = ['pdf', 'doc', 'docx', 'jpg', 'jpeg', 'png'];
        $filename = $_FILES['document_file']['name'];
        $file_ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
        
        if (in_array($file_ext, $allowed)) {
            $new_filename = uniqid() . '.' . $file_ext;
            $upload_path = '../../uploads/loan_documents/';
            
            // Create directory if it doesn't exist
            if (!file_exists($upload_path)) {
                mkdir($upload_path, 0777, true);
            }
            
            if (move_uploaded_file($_FILES['document_file']['tmp_name'], $upload_path . $new_filename)) {
                try {
                    $stmt = $db->prepare("INSERT INTO loan_documents (loan_id, document_name, document_type, file_path) VALUES (?, ?, ?, ?)");
                    $stmt->execute([$loan_id, $document_name, $document_type, $new_filename]);
                    echo json_encode(['success' => true]);
                } catch (Exception $e) {
                    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
                }
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to upload file.']);
            }
        } else {
            echo json_encode(['success' => false, 'message' => 'Invalid file type. Allowed types: ' . implode(', ', $allowed)]);
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'No file uploaded or file upload error.']);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid action']);
}
?>
