<?php
require_once 'config/db.php';
require_once 'includes/auth.php';
require_once 'includes/functions.php';
requireLogin();

$settings   = getSettings($conn);
$borrowers  = getAllBorrowers($conn);
$preselect  = intval($_GET['borrower_id'] ?? 0);
$errors     = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $borrower_id   = intval($_POST['borrower_id'] ?? 0);
    $loan_amount   = floatval($_POST['loan_amount'] ?? 0);
    $interest_rate = floatval($_POST['interest_rate'] ?? 0);
    $term          = intval($_POST['term'] ?? 0);
    $payment_mode  = $_POST['payment_mode'] ?? 'monthly';
    $release_date  = $_POST['release_date'] ?? date('Y-m-d');
    $due_date      = $_POST['due_date'] ?? '';

    // Fallback: calculate due_date server-side if JS didn't populate it
    if (empty($due_date) && !empty($release_date) && $term > 0) {
        $d = new DateTime($release_date);
        if ($payment_mode === 'daily')       $d->modify("+{$term} days");
        elseif ($payment_mode === 'weekly')  $d->modify("+" . ($term * 7) . " days");
        else                                 $d->modify("+{$term} months");
        $due_date = $d->format('Y-m-d');
    }
    $penalty       = floatval($_POST['penalty'] ?? 0);

    if (!$borrower_id)   $errors[] = 'Please select a borrower';
    if ($loan_amount<=0) $errors[] = 'Loan amount must be greater than 0';
    if ($term<=0)        $errors[] = 'Term must be greater than 0';
    if (!in_array($payment_mode,['daily','weekly','monthly'])) $errors[] = 'Invalid payment mode';

    // Improvement 12: block duplicate active loans
    if ($borrower_id && empty($errors)) {
        $activeCheck = fetchOne($conn,
            "SELECT COUNT(*) as cnt FROM loans WHERE borrower_id = ? AND status NOT IN ('paid')",
            [$borrower_id], "i");
        if ($activeCheck && $activeCheck['cnt'] > 0) {
            $errors[] = 'This borrower already has an active loan. Please settle it before creating a new one.';
        }
    }

    if (empty($errors)) {
        try {
            $loan_id = addLoan($conn, $borrower_id, $loan_amount, $interest_rate, $term,
                                $release_date, $due_date, $payment_mode, $penalty);
            logActivity($conn, $_SESSION['user_id'], 'add_loan',
                "Created loan ₱$loan_amount for borrower ID $borrower_id");
            header('Location: /cash_lending/loan-details.php?id='.$loan_id.'&success=1');
            exit();
        } catch (Exception $e) {
            $errors[] = 'Error: '.$e->getMessage();
        }
    }
}

include 'includes/header.php';
include 'includes/sidebar.php';
?>
<div class="row mb-4">
    <div class="col-lg-8"><h3><i class="fas fa-file-contract"></i> New Loan</h3></div>
</div>

<div class="row">
<div class="col-lg-7">
<div class="card">
<div class="card-body p-4">
    <?php if (!empty($errors)): ?>
        <div class="alert alert-danger"><ul class="mb-0">
            <?php foreach($errors as $e): ?><li><?php echo htmlspecialchars($e); ?></li><?php endforeach; ?>
        </ul></div>
    <?php endif; ?>

    <form method="POST">
        <div class="mb-3">
            <label class="form-label fw-semibold">Borrower <span class="text-danger">*</span></label>
            <select class="form-select" name="borrower_id" required>
                <option value="">-- Select Borrower --</option>
                <?php foreach ($borrowers as $b): ?>
                    <option value="<?php echo $b['id']; ?>"
                        <?php echo ($preselect===$b['id']||($_POST['borrower_id']??0)==$b['id'])?'selected':''; ?>>
                        <?php echo htmlspecialchars($b['first_name'].' '.$b['last_name']); ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="row">
            <div class="col-md-6 mb-3">
                <label class="form-label fw-semibold">Loan Amount <span class="text-danger">*</span></label>
                <div class="input-group">
                    <span class="input-group-text">₱</span>
                    <input type="number" class="form-control" name="loan_amount" id="loanAmount"
                           step="0.01" min="1" required
                           value="<?php echo htmlspecialchars($_POST['loan_amount']??''); ?>"
                           oninput="calculateLoan()">
                </div>
            </div>
            <div class="col-md-6 mb-3">
                <label class="form-label fw-semibold">Interest Rate (%)</label>
                <input type="number" class="form-control" name="interest_rate" id="interestRate"
                       step="0.01" min="0"
                       value="<?php echo htmlspecialchars($_POST['interest_rate']??$settings['default_interest']??10); ?>"
                       oninput="calculateLoan()">
            </div>
        </div>

        <div class="row">
            <div class="col-md-6 mb-3">
                <label class="form-label fw-semibold">Term <span class="text-danger">*</span></label>
                <div class="input-group">
                    <input type="number" class="form-control" name="term" id="term"
                           min="1" required
                           value="<?php echo htmlspecialchars($_POST['term']??''); ?>"
                           oninput="calculateLoan()">
                    <span class="input-group-text" id="termUnit">months</span>
                </div>
            </div>
            <div class="col-md-6 mb-3">
                <label class="form-label fw-semibold">Payment Mode</label>
                <select class="form-select" name="payment_mode" id="paymentMode" onchange="calculateLoan()">
                    <?php foreach(['monthly'=>'Monthly','weekly'=>'Weekly','daily'=>'Daily'] as $v=>$l): ?>
                        <option value="<?php echo $v; ?>"
                            <?php echo ($_POST['payment_mode']??'monthly')===$v?'selected':''; ?>>
                            <?php echo $l; ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
        </div>

        <div class="row">
            <div class="col-md-6 mb-3">
                <label class="form-label fw-semibold">Release Date</label>
                <input type="date" class="form-control" name="release_date" id="releaseDate"
                       value="<?php echo htmlspecialchars($_POST['release_date']??date('Y-m-d')); ?>"
                       oninput="calculateLoan()">
            </div>
            <div class="col-md-6 mb-3">
                <label class="form-label fw-semibold">Due Date</label>
                <input type="date" class="form-control" name="due_date" id="dueDate" readonly
                       style="background:#f8f9fa;"
                       value="<?php echo htmlspecialchars($_POST['due_date']??''); ?>">
                <small class="text-muted">Auto-calculated</small>
            </div>
        </div>

        <div class="mb-3">
            <label class="form-label fw-semibold">Penalty Rate (%)</label>
            <input type="number" class="form-control" name="penalty" step="0.01" min="0"
                   value="<?php echo htmlspecialchars($_POST['penalty']??$settings['penalty']??2); ?>">
        </div>

        <!-- Live calculation preview -->
        <div class="card border-primary mb-4 d-none" id="calcPreview">
            <div class="card-body py-2">
                <div class="row text-center">
                    <div class="col-4">
                        <div class="text-muted small">Total Interest</div>
                        <div class="fw-bold text-warning" id="previewInterest">—</div>
                    </div>
                    <div class="col-4">
                        <div class="text-muted small">Total Payable</div>
                        <div class="fw-bold text-primary" id="previewTotal">—</div>
                    </div>
                    <div class="col-4">
                        <div class="text-muted small">Per <span id="previewModeLabel">Month</span></div>
                        <div class="fw-bold text-success" id="previewInstall">—</div>
                    </div>
                </div>
            </div>
        </div>

        <div class="d-flex gap-2">
            <button type="submit" class="btn btn-primary px-4">
                <i class="fas fa-save"></i> Create Loan
            </button>
            <a href="/cash_lending/loans.php" class="btn btn-outline-secondary">
                <i class="fas fa-times"></i> Cancel
            </a>
        </div>
    </form>
</div>
</div>
</div>
</div>

<script>
function calculateLoan() {
    const amount   = parseFloat(document.getElementById('loanAmount').value)   || 0;
    const rate     = parseFloat(document.getElementById('interestRate').value) || 0;
    const term     = parseInt(document.getElementById('term').value)           || 0;
    const mode     = document.getElementById('paymentMode').value;
    const release  = document.getElementById('releaseDate').value;

    if (!amount || !term) {
        document.getElementById('calcPreview').classList.add('d-none');
        return;
    }

    // Due date
    if (release) {
        const d = new Date(release);
        if (mode === 'daily')        d.setDate(d.getDate() + term);
        else if (mode === 'weekly')  d.setDate(d.getDate() + term * 7);
        else                         d.setMonth(d.getMonth() + term);
        document.getElementById('dueDate').value = d.toISOString().split('T')[0];
    }

    // Term unit label
    const units = {daily:'Day', weekly:'Week', monthly:'Month'};
    document.getElementById('termUnit').textContent = mode === 'daily' ? 'days' : mode === 'weekly' ? 'weeks' : 'months';
    document.getElementById('previewModeLabel').textContent = units[mode];

    // term is already in the correct unit (days/weeks/months)
    let installments = term;

    // Interest rate is MONTHLY — convert term to months then multiply
    let termInMonths;
    if (mode === 'daily')       termInMonths = term / 30;
    else if (mode === 'weekly') termInMonths = (term * 7) / 30;
    else                        termInMonths = term;   // already in months

    const interest   = amount * (rate / 100) * termInMonths;
    const total      = amount + interest;
    const installAmt = total / installments;

    const fmt = v => '₱' + v.toLocaleString('en-PH', {minimumFractionDigits:2, maximumFractionDigits:2});
    document.getElementById('previewInterest').textContent = fmt(interest);
    document.getElementById('previewTotal').textContent    = fmt(total);
    document.getElementById('previewInstall').textContent  = fmt(installAmt);
    document.getElementById('calcPreview').classList.remove('d-none');
}

document.addEventListener('DOMContentLoaded', calculateLoan);
</script>
<?php include 'includes/footer.php'; ?>
