<?php
require_once __DIR__ . '/../config/auth.php';
require_once __DIR__ . '/../includes/functions.php';
requirePermission('repair_payment');

$pdo = getDB();
$user = currentUser();

$job_id = isset($_GET['job_id']) ? (int)$_GET['job_id'] : 0;
if (!$job_id) { $_SESSION['error'] = 'Invalid job ID.'; header('Location: repair_jobs.php'); exit; }

$stmt = $pdo->prepare("SELECT rj.*, c.name as customer_name, c.phone as customer_phone FROM repair_jobs rj LEFT JOIN customers c ON rj.customer_id = c.id WHERE rj.id = ?");
$stmt->execute([$job_id]);
$job = $stmt->fetch();
if (!$job) { $_SESSION['error'] = 'Job not found.'; header('Location: repair_jobs.php'); exit; }

if (in_array($job['repair_status'], ['Delivered', 'Cancelled', 'Cannot Repair'])) {
    $_SESSION['error'] = 'Cannot collect payment for a ' . $job['repair_status'] . ' job.';
    header('Location: view_repair_job.php?id=' . $job_id); exit;
}

// Handle payment submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_payment'])) {
    $payment_amount = (float)($_POST['payment_amount'] ?? 0);
    $payment_method = $_POST['payment_method'] ?? 'Cash';
    $payment_note = trim($_POST['payment_note'] ?? '');

    if ($payment_amount <= 0) {
        $_SESSION['error'] = 'Payment amount must be greater than zero.';
    } else {
        try {
            $pdo->beginTransaction();

            // Check for overpayment
            $current_due = $job['due_amount'];
            if ($payment_amount > $current_due) {
                // Check if user is Super Admin or Admin to allow overpayment
                $is_admin = in_array($user['role_name'], ['Super Admin', 'Admin']);
                if (!$is_admin) {
                    throw new Exception("Overpayment not allowed. Due amount is " . formatCurrency($current_due) . ".");
                }
            }

            // Generate payment number
            $payment_no = generatePaymentNo();

            $stmt = $pdo->prepare("INSERT INTO payments (payment_no, payment_type, reference_id, customer_id, amount, payment_method, payment_date, note, received_by) VALUES (?, 'repair', ?, ?, ?, ?, NOW(), ?, ?)");
            $stmt->execute([$payment_no, $job_id, $job['customer_id'], $payment_amount, $payment_method, $payment_note, $user['id']]);

            // Update repair job paid/due amounts
            $new_paid = $job['paid_amount'] + $payment_amount;
            $new_due = $job['final_amount'] - $new_paid;
            if ($new_due < 0) $new_due = 0;

            $pdo->prepare("UPDATE repair_jobs SET paid_amount = ?, due_amount = ?, updated_at = NOW() WHERE id = ?")->execute([$new_paid, $new_due, $job_id]);

            // Update customer balance if payment collected
            if ($job['customer_id']) {
                $pdo->prepare("UPDATE customers SET current_balance = current_balance - ? WHERE id = ?")->execute([$payment_amount, $job['customer_id']]);
            }

            $pdo->commit();

            // Update session variable for refreshed page
            $job['paid_amount'] = $new_paid;
            $job['due_amount'] = $new_due;

            $_SESSION['success'] = "Payment of " . formatCurrency($payment_amount) . " collected successfully.";
            header("Location: view_repair_job.php?id=$job_id"); exit;

        } catch (Exception $e) {
            $pdo->rollBack();
            $_SESSION['error'] = 'Error: ' . $e->getMessage();
        }
    }
}

include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>
<div class="content-wrapper">
    <div class="container-fluid">
        <h4 class="page-title"><i class="fas fa-money-bill me-2"></i>Collect Payment - <?= htmlspecialchars($job['job_no']) ?></h4>

        <?php if (isset($_SESSION['success'])): ?><div class="alert alert-success alert-dismissible"><?= $_SESSION['success']; unset($_SESSION['success']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>
        <?php if (isset($_SESSION['error'])): ?><div class="alert alert-danger alert-dismissible"><?= $_SESSION['error']; unset($_SESSION['error']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>

        <div class="row">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header"><i class="fas fa-file-invoice me-2"></i>Job Summary</div>
                    <div class="card-body">
                        <table class="table table-sm">
                            <tr><td width="140">Job No:</td><td><strong><?= htmlspecialchars($job['job_no']) ?></strong></td></tr>
                            <tr><td>Customer:</td><td><?= htmlspecialchars($job['customer_name'] ?? '-') ?> (<?= htmlspecialchars($job['customer_phone'] ?? '') ?>)</td></tr>
                            <tr><td>Device:</td><td><?= htmlspecialchars($job['device_brand'] ?? '') ?> <?= htmlspecialchars($job['device_model'] ?? '') ?></td></tr>
                            <tr><td>Status:</td><td><?= getStatusBadge($job['repair_status']) ?></td></tr>
                        </table>
                        <hr>
                        <table class="table table-sm">
                            <tr><td>Parts Total:</td><td class="text-end"><?= formatCurrency($job['parts_total']) ?></td></tr>
                            <tr><td>Labour Charge:</td><td class="text-end"><?= formatCurrency($job['labour_charge']) ?></td></tr>
                            <tr><td>Discount:</td><td class="text-end">-<?= formatCurrency($job['discount_amount']) ?></td></tr>
                            <tr class="fw-bold"><td>Final Amount:</td><td class="text-end"><?= formatCurrency($job['final_amount']) ?></td></tr>
                            <tr><td>Already Paid:</td><td class="text-end text-success"><?= formatCurrency($job['paid_amount']) ?></td></tr>
                            <tr class="text-danger fw-bold"><td>Due Amount:</td><td class="text-end"><?= formatCurrency($job['due_amount']) ?></td></tr>
                        </table>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header"><i class="fas fa-credit-card me-2"></i>Payment Details</div>
                    <div class="card-body">
                        <form method="POST">
                            <div class="mb-3">
                                <label class="form-label">Payment Amount <span class="text-danger">*</span></label>
                                <div class="input-group">
                                    <span class="input-group-text"><?= htmlspecialchars(getSetting('currency_symbol', 'Rs.')) ?></span>
                                    <input type="number" step="0.01" name="payment_amount" id="paymentAmount" class="form-control form-control-lg" value="<?= $job['due_amount'] ?>" min="0.01" max="<?= $job['due_amount'] ?>" required>
                                </div>
                                <div class="form-text">Due amount: <?= formatCurrency($job['due_amount']) ?></div>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Payment Method <span class="text-danger">*</span></label>
                                <select name="payment_method" class="form-select" required>
                                    <option value="Cash">Cash</option>
                                    <option value="Card">Card</option>
                                    <option value="Bank Transfer">Bank Transfer</option>
                                    <option value="Online Payment">Online Payment</option>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Note</label>
                                <textarea name="payment_note" class="form-control" rows="2" placeholder="Optional payment note"></textarea>
                            </div>
                            <div class="d-flex gap-2">
                                <button type="submit" name="save_payment" class="btn btn-success btn-lg"><i class="fas fa-check me-1"></i> Save Payment</button>
                                <a href="view_repair_job.php?id=<?= $job_id ?>" class="btn btn-secondary btn-lg">Cancel</a>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
$('#paymentAmount').on('input', function() {
    var due = <?= $job['due_amount'] ?>;
    var val = parseFloat($(this).val()) || 0;
    if (val > due) {
        $(this).val(due);
    }
});
</script>

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