<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

echo "START"; exit;

require_once __DIR__ . '/../../../includes/auth.php';
requireLogin();

require_once __DIR__ . '/../../../config/database.php';

if (!isset($_GET['invoice_id']) || !is_numeric($_GET['invoice_id'])) {
    die("Invoice ID missing.");
}

$invoiceId = (int)$_GET['invoice_id'];

/* ===============================
   LOAD INVOICE
================================= */
$stmt = $pdo->prepare("
    SELECT *
    FROM invoices
    WHERE id = ?
    LIMIT 1
");
$stmt->execute([$invoiceId]);
$invoice = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$invoice) {
    die("Invoice not found.");
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $amount = isset($_POST['amount']) ? (float)$_POST['amount'] : 0;
    $paymentDate = !empty($_POST['payment_date']) ? $_POST['payment_date'] : date('Y-m-d');
    $method = isset($_POST['method']) ? trim($_POST['method']) : '';
    $reference = isset($_POST['reference']) ? trim($_POST['reference']) : '';
    $notes = isset($_POST['notes']) ? trim($_POST['notes']) : '';

    if ($amount <= 0) {
        die("Invalid payment amount.");
    }

    /* ===============================
       INSERT PAYMENT
    ================================= */
    $stmt = $pdo->prepare("
        INSERT INTO invoice_payments
        (invoice_id, company_id, amount, payment_date, method, reference, notes, created_by)
        VALUES (?,?,?,?,?,?,?,?)
    ");

    $stmt->execute([
        $invoiceId,
        $invoice['company_id'] ?? 0, // safe fallback (since you're removing company)
        $amount,
        $paymentDate,
        $method,
        $reference,
        $notes,
        $_SESSION['user_id'] ?? 0
    ]);

    /* ===============================
       CHECK TOTAL PAID
    ================================= */
    $stmt = $pdo->prepare("
        SELECT SUM(amount)
        FROM invoice_payments
        WHERE invoice_id = ?
    ");
    $stmt->execute([$invoiceId]);
    $totalPaid = (float)($stmt->fetchColumn() ?? 0);

    if ($totalPaid >= (float)$invoice['total']) {
        $pdo->prepare("
            UPDATE invoices
            SET status = 'PAID'
            WHERE id = ?
        ")->execute([$invoiceId]);
    }

    header("Location: invoice_view.php?id=" . $invoiceId);
    exit;
}
?>

<?php require_once __DIR__ . '/../../../includes/header.php'; ?>
<?php require_once __DIR__ . '/../../../includes/sidebar.php'; ?>

<div class="main-content">

    <div class="page-header">
        <h2>Add Payment — Invoice #<?= htmlspecialchars($invoice['invoice_number']) ?></h2>
    </div>

    <form method="POST" class="card-form">

        <label>Payment Amount</label>
        <input type="number" step="0.01" name="amount" required>

        <label>Payment Date</label>
        <input type="date" name="payment_date" value="<?= date('Y-m-d') ?>" required>

        <label>Payment Method</label>
        <input type="text" name="method" placeholder="EFT / Cash / Card">

        <label>Reference</label>
        <input type="text" name="reference" placeholder="Transaction Ref">

        <label>Notes</label>
        <textarea name="notes" rows="3"></textarea>

        <button type="submit" class="btn btn-primary">
            Save Payment
        </button>

    </form>

</div>

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