<?php
session_start();
require_once 'includes/auth_check.php';

$page = 'loans';
$database = new Database();
$db = $database->getConnection();

$success_message = '';
$error_message = '';

// Get loan ID from URL and validate it
$loan_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if (!$loan_id) {
    header("Location: loans.php");
    exit();
}

// --- HANDLE LOAN PAYMENT ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['make_payment'])) {
    $payment_amount = filter_input(INPUT_POST, 'payment_amount', FILTER_VALIDATE_FLOAT);
    $user_id = $_SESSION['user_id'];

    // Fetch user's current balance and the loan details in one go for validation
    $stmt = $db->prepare("SELECT u.balance, l.total_amount, l.amount_paid FROM users u JOIN loans l ON u.id = l.user_id WHERE u.id = ? AND l.id = ?");
    $stmt->execute([$user_id, $loan_id]);
    $data = $stmt->fetch(PDO::FETCH_ASSOC);

    $current_balance = $data['balance'];
    $remaining_balance = $data['total_amount'] - $data['amount_paid'];

    // Validation
    if ($payment_amount <= 0) {
        $error_message = "Payment amount must be positive.";
    } elseif ($payment_amount > $current_balance) {
        $error_message = "Insufficient funds. Your balance is lower than the payment amount.";
    } elseif ($payment_amount > $remaining_balance) {
        $error_message = "Payment amount cannot be greater than the remaining loan balance.";
    } else {
        // All checks passed, proceed with database transaction
        try {
            $db->beginTransaction();

            // 1. Deduct from user's main balance
            $new_balance = $current_balance - $payment_amount;
            $stmt1 = $db->prepare("UPDATE users SET balance = ? WHERE id = ?");
            $stmt1->execute([$new_balance, $user_id]);

            // 2. Add record to loan_payments
            $stmt2 = $db->prepare("INSERT INTO loan_payments (loan_id, amount, payment_date) VALUES (?, ?, CURDATE())");
            $stmt2->execute([$loan_id, $payment_amount]);

            // 3. Update amount_paid in loans table
            $new_amount_paid = $data['amount_paid'] + $payment_amount;
            $stmt3 = $db->prepare("UPDATE loans SET amount_paid = ? WHERE id = ?");
            $stmt3->execute([$new_amount_paid, $loan_id]);

            // 4. Create a debit transaction log
            $description = "Loan Payment for Loan ID #" . $loan_id;
            $stmt4 = $db->prepare("INSERT INTO transactions (user_id, type, amount, currency, description, status, transaction_type) VALUES (?, 'debit', ?, ?, ?, 'completed', 'loan_payment')");
            $stmt4->execute([$user_id, $payment_amount, $user['currency'], $description]);
            
            // If all queries were successful, commit the transaction
            $db->commit();
            $success_message = "Your payment of " . htmlspecialchars($user['currency']) . " " . number_format($payment_amount, 2) . " was successful!";

        } catch (Exception $e) {
            // If any query fails, roll back all changes
            $db->rollBack();
            $error_message = "A critical error occurred during the transaction. Please try again.";
            error_log("Loan Payment Transaction Error: " . $e->getMessage());
        }
    }
}


// Security Check: Fetch the loan details ONLY if it belongs to the logged-in user
$stmt = $db->prepare("SELECT * FROM loans WHERE id = ? AND user_id = ?");
$stmt->execute([$loan_id, $_SESSION['user_id']]);
$loan = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$loan) {
    $_SESSION['error_message'] = "Loan not found or permission denied.";
    header("Location: loans.php");
    exit();
}

// Fetch payment history for this specific loan
$payment_stmt = $db->prepare("SELECT * FROM loan_payments WHERE loan_id = ? ORDER BY payment_date DESC");
$payment_stmt->execute([$loan_id]);
$payments = $payment_stmt->fetchAll(PDO::FETCH_ASSOC);

// Calculate loan progress
$remaining_balance = $loan['total_amount'] - $loan['amount_paid'];
$progress_percentage = ($loan['total_amount'] > 0) ? ($loan['amount_paid'] / $loan['total_amount']) * 100 : 0;

include 'includes/header.php';
include 'includes/sidebar.php';
?>

<style>
/* Loan Details Page Styles */
:root {
    --primary-color: #4f46e5;
    --border-color: #e2e8f0;
    --success-color: #10b981;
}
.main-content { background-color: #f8fafc; }

.summary-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 1.5rem;
}
.summary-card {
    background-color: white;
    border: 1px solid var(--border-color);
    border-radius: 1rem;
    padding: 1.5rem;
}
.summary-card .label {
    color: #64748b;
    font-size: 0.875rem;
    margin-bottom: 0.5rem;
    display: flex;
    align-items: center;
}
.summary-card .label i {
    margin-right: 0.5rem;
}
.summary-card .value {
    font-size: 1.75rem;
    font-weight: 600;
}
.progress-bar-container {
    height: 8px;
    background-color: #e9ecef;
    border-radius: 999px;
    overflow: hidden;
    margin-top: 1rem;
}
.progress-bar-fill {
    height: 100%;
    background-color: var(--primary-color);
    border-radius: 999px;
}
.loan-card.paid-off .progress-bar-fill {
    background-color: var(--success-color);
}
.table-hover tbody tr:hover {
    background-color: #f8fafc;
}
</style>

<div class="main-content">
    <div class="container py-4">
        <div class="d-flex align-items-center mb-4">
            <a href="loans.php" class="btn btn-light me-3" style="border-radius: 50%; width: 40px; height: 40px; display: grid; place-content: center;"><i class='bx bx-arrow-back'></i></a>
            <div>
                <h1 class="h3 mb-0"><?php echo htmlspecialchars($loan['loan_type']); ?> Details</h1>
                <p class="text-muted mb-0">Loan Account ending in ...<?php echo substr(abs(crc32($loan['id'])), 0, 4); ?></p>
            </div>
        </div>

        <?php if (!empty($success_message)): ?>
            <div class="alert alert-success"><?php echo $success_message; ?></div>
        <?php endif; ?>
        <?php if (!empty($error_message)): ?>
            <div class="alert alert-danger"><?php echo $error_message; ?></div>
        <?php endif; ?>

        <!-- Loan Summary Grid -->
        <div class="summary-grid mb-4">
            <div class="summary-card">
                <div class="label"><i class='bx bx-wallet'></i> Remaining Balance</div>
                <div class="value text-primary"><?php echo htmlspecialchars($user['currency']); ?> <?php echo number_format($remaining_balance, 2); ?></div>
            </div>
            <div class="summary-card">
                <div class="label"><i class='bx bx-calendar-check'></i> Next Payment</div>
                <div class="value"><?php echo $loan['next_payment_date'] ? date('M d, Y', strtotime($loan['next_payment_date'])) : 'N/A'; ?></div>
            </div>
            <div class="summary-card">
                <div class="label"><i class='bx bx-line-chart'></i> Interest Rate</div>
                <div class="value"><?php echo htmlspecialchars($loan['interest_rate']); ?>%</div>
            </div>
        </div>

        <!-- Progress Card -->
        <div class="card mb-4">
            <div class="card-body">
                <h5 class="card-title">Loan Progress</h5>
                <div class="d-flex justify-content-between mb-1">
                    <span class="text-muted">Paid: <?php echo htmlspecialchars($user['currency']); ?> <?php echo number_format($loan['amount_paid'], 2); ?></span>
                    <span class="text-muted">Total: <?php echo htmlspecialchars($user['currency']); ?> <?php echo number_format($loan['total_amount'], 2); ?></span>
                </div>
                <div class="progress-bar-container">
                    <div class="progress-bar-fill" style="width: <?php echo $progress_percentage; ?>%;"></div>
                </div>
            </div>
        </div>

        <!-- Payment History -->
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">Payment History</h5>
                <?php if ($loan['status'] == 'active'): ?>
                    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#paymentModal">Make a Payment</button>
                <?php endif; ?>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover mb-0">
                        <thead>
                            <tr>
                                <th>Payment Date</th>
                                <th>Notes</th>
                                <th class="text-end">Amount</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($payments)): ?>
                                <tr>
                                    <td colspan="3" class="text-center text-muted py-4">No payment history found for this loan.</td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($payments as $payment): ?>
                                    <tr>
                                        <td><?php echo date('F j, Y', strtotime($payment['payment_date'])); ?></td>
                                        <td><?php echo htmlspecialchars($payment['notes'] ?? 'Standard Payment'); ?></td>
                                        <td class="text-end fw-bold"><?php echo htmlspecialchars($user['currency']); ?> <?php echo number_format($payment['amount'], 2); ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Make Payment Modal -->
<div class="modal fade" id="paymentModal" tabindex="-1" aria-labelledby="paymentModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="paymentModalLabel">Make a Loan Payment</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="POST" action="loan-details.php?id=<?php echo $loan_id; ?>">
                <div class="modal-body">
                    <p>Your current account balance is: <strong class="text-success"><?php echo htmlspecialchars($user['currency']); ?> <?php echo number_format($user['balance'], 2); ?></strong></p>
                    <p>Remaining loan balance: <strong><?php echo htmlspecialchars($user['currency']); ?> <?php echo number_format($remaining_balance, 2); ?></strong></p>
                    <hr>
                    <div class="mb-3">
                        <label for="payment_amount" class="form-label">Payment Amount</label>
                        <div class="input-group">
                            <span class="input-group-text"><?php echo htmlspecialchars($user['currency']); ?></span>
                            <input type="number" class="form-control" id="payment_amount" name="payment_amount" step="0.01" min="0.01" max="<?php echo $remaining_balance; ?>" required>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" name="make_payment" class="btn btn-primary">Confirm Payment</button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php include 'includes/footer.php'; ?>
