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

$page_title = 'New Loan';
$active_nav = 'loans';
$errors = [];

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

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');
    $penalty        = floatval($_POST['penalty'] ?? 0);

    // Calculate due_date server-side (same logic as desktop)
    $due_date = $_POST['due_date'] ?? '';
    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');
    }

    if (!$borrower_id)   $errors[] = 'Select a borrower';
    if ($loan_amount<=0) $errors[] = 'Loan amount required';
    if ($term<=0)        $errors[] = 'Term required';

    // 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. Settle it before creating a new one.';
        }
    }

    if (empty($errors)) {
        try {
            addLoan($conn, $borrower_id, $loan_amount, $interest_rate, $term,
                    $release_date, $due_date, $payment_mode, $penalty);
            header('Location: /cash_lending/mobile/loans.php?success=1');
            exit();
        } catch (Exception $e) {
            $errors[] = 'Error: ' . $e->getMessage();
        }
    }
}

include 'header.php';
?>

<?php if (!empty($errors)): ?>
    <div class="alert alert-danger">
        <i class="fas fa-exclamation-circle"></i>
        <?php echo implode('<br>', array_map('htmlspecialchars', $errors)); ?>
    </div>
<?php endif; ?>

<form method="POST">
    <div class="form-group">
        <label class="form-label">Borrower <span class="required">*</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_borrower === $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="form-group">
        <label class="form-label">Loan Amount <span class="required">*</span></label>
        <input type="number" class="form-control" name="loan_amount" step="0.01" min="1" required
               value="<?php echo htmlspecialchars($_POST['loan_amount'] ?? ''); ?>" placeholder="0.00">
    </div>

    <div class="form-group">
        <label class="form-label">Interest Rate (%)</label>
        <input type="number" class="form-control" name="interest_rate" step="0.01" min="0"
               value="<?php echo htmlspecialchars($_POST['interest_rate'] ?? $settings['default_interest'] ?? '10'); ?>">
    </div>

    <div class="form-group">
        <label class="form-label">Term (months) <span class="required">*</span></label>
        <input type="number" class="form-control" name="term" min="1" required
               value="<?php echo htmlspecialchars($_POST['term'] ?? ''); ?>">
    </div>

    <div class="form-group">
        <label class="form-label">Payment Mode</label>
        <select class="form-select" name="payment_mode">
            <?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 class="form-group">
        <label class="form-label">Release Date</label>
        <input type="date" class="form-control" name="release_date" id="mReleaseDate"
               value="<?php echo htmlspecialchars($_POST['release_date'] ?? date('Y-m-d')); ?>"
               oninput="calcMobileDue()">
    </div>
    <div class="form-group">
        <label class="form-label">Due Date <small style="color:var(--muted);">(auto-calculated)</small></label>
        <input type="date" class="form-control" name="due_date" id="mDueDate" readonly
               style="background:#f3f4f8;" value="<?php echo htmlspecialchars($_POST['due_date'] ?? ''); ?>">
    </div>

    <div class="form-group">
        <label class="form-label">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>

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

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