<?php

ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(E_ALL);

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

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

$company_id = $_SESSION['company_id'] ?? 0;
$user_id    = $_SESSION['user_id'] ?? 0;

/* ===============================
VALIDATE INPUT
================================ */

$invoice_id = isset($_POST['invoice_id']) ? (int)$_POST['invoice_id'] : 0;
$amount     = isset($_POST['amount']) ? (float)$_POST['amount'] : 0;
$method     = trim($_POST['method'] ?? '');
$reference  = trim($_POST['reference'] ?? '');

if(!$invoice_id){
die("Invalid invoice.");
}

if($amount <= 0){
die("Payment amount must be greater than zero.");
}


/* ===============================
SAVE PAYMENT
================================ */

$stmt = $pdo->prepare("
INSERT INTO invoice_payments
(company_id,invoice_id,amount,payment_method,reference,created_by)
VALUES
(?,?,?,?,?,?)
");

$stmt->execute([
$company_id,
$invoice_id,
$amount,
$method,
$reference,
$user_id
]);


/* ===============================
FETCH INVOICE TOTALS
================================ */

$stmt = $pdo->prepare("
SELECT total, paid_total
FROM invoices
WHERE id = ?
AND company_id = ?
");

$stmt->execute([$invoice_id,$company_id]);

$inv = $stmt->fetch(PDO::FETCH_ASSOC);

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

$total     = (float)$inv['total'];
$paid_total = (float)($inv['paid_total'] ?? 0);


/* ===============================
CALCULATE NEW TOTALS
================================ */

$new_paid = $paid_total + $amount;

$balance = $total - $new_paid;

$status = 'UNPAID';

if($new_paid > 0 && $balance > 0){
$status = 'PARTIAL';
}

if($balance <= 0){
$status = 'PAID';
$balance = 0;
}


/* ===============================
UPDATE INVOICE
================================ */

$stmt = $pdo->prepare("
UPDATE invoices
SET
paid_total = ?,
balance = ?,
payment_status = ?
WHERE id = ?
AND company_id = ?
");

$stmt->execute([
$new_paid,
$balance,
$status,
$invoice_id,
$company_id
]);


/* ===============================
REDIRECT
================================ */

header("Location: ../invoices/view.php?id=".$invoice_id);
exit;