<?php
require_once __DIR__ . '/../../app/core/bootstrap.php';
require_once __DIR__ . '/../../app/core/project_permissions.php';
require_once __DIR__ . '/../../app/core/project_menu.php';
require_once __DIR__ . '/../../app/core/i18n.php';
auth_require_login();
$pdo = crm_pdo();
$projectId = (int)($_GET['project_id'] ?? $_POST['project_id'] ?? 0);
if ($projectId <= 0) die('Missing project_id.');
gp_require_project_edit($pdo, $projectId);

$stmt = $pdo->prepare("SELECT p.*, c.name AS customer_name FROM projects p LEFT JOIN customers c ON c.id = p.customer_id WHERE p.id = :id LIMIT 1");
$stmt->execute([':id' => $projectId]);
$project = $stmt->fetch();
if (!$project) die('Project not found.');

$errors = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $paymentType = trim((string)($_POST['payment_type'] ?? 'payment'));
    $amount = (float)($_POST['amount'] ?? 0);
    $paymentDate = trim((string)($_POST['payment_date'] ?? ''));
    $notes = trim((string)($_POST['notes'] ?? ''));
    if ($amount <= 0) $errors[] = 'Amount must be greater than zero.';
    if ($paymentDate === '') $errors[] = 'Payment date is required.';
    if (!$errors) {
        $stmt = $pdo->prepare("INSERT INTO project_payments (project_id, payment_type, amount, payment_date, notes) VALUES (:pid,:typ,:amt,:dt,:notes)");
        $stmt->execute([
            ':pid' => $projectId,
            ':typ' => $paymentType,
            ':amt' => $amount,
            ':dt' => $paymentDate,
            ':notes' => $notes !== '' ? $notes : null,
        ]);
        redirect('/public/projects/payments.php?project_id=' . $projectId);
    }
}

$stmt = $pdo->prepare("SELECT * FROM project_payments WHERE project_id = :pid ORDER BY payment_date DESC, id DESC");
$stmt->execute([':pid' => $projectId]);
$rows = $stmt->fetchAll();

$stmt = $pdo->prepare("SELECT COALESCE(SUM(amount),0) FROM project_payments WHERE project_id = :pid AND payment_type IN ('deposit','payment')");
$stmt->execute([':pid' => $projectId]);
$totalPaid = (float)$stmt->fetchColumn();
$budget = (float)($project['budget'] ?? 0);
$balance = $budget - $totalPaid;

$page_title = 'Project payments';
include __DIR__ . '/../includes/header.php';
?>
<div class="page-header">
  <div class="page-header-title">
    <h1>Payments · <?php echo h($project['title']); ?></h1>
    <span><?php echo h($project['code']); ?> · <?php echo h($project['customer_name']); ?></span>
  </div>
  <div class="page-header-actions">
    <a class="btn btn-secondary btn-sm" href="/public/projects/edit.php?id=<?php echo (int)$projectId; ?>">Back to project</a>
  </div>
</div>

<div class="grid-2" style="margin-bottom:14px">
  <div class="card"><div class="small">Budget</div><div style="font-size:2rem;font-weight:700">€ <?php echo h(number_format($budget, 2)); ?></div></div>
  <div class="card"><div class="small">Paid / Balance</div><div style="font-size:1.2rem;font-weight:700">€ <?php echo h(number_format($totalPaid, 2)); ?> / € <?php echo h(number_format($balance, 2)); ?></div></div>
</div>

<?php gp_render_project_menu($pdo, $projectId); ?>

<div class="grid-2">
  <div class="card">
    <div class="page-header-title"><h1 style="font-size:1.05rem">Add payment</h1></div>
    <?php if ($errors): ?><div class="alert-danger"><?php echo h(implode(' ', $errors)); ?></div><?php endif; ?>
    <form method="post">
      <input type="hidden" name="project_id" value="<?php echo (int)$projectId; ?>">
      <div class="form-grid">
        <div class="form-group"><label>Type</label><select name="payment_type"><option value="deposit">Deposit</option><option value="payment">Payment</option><option value="refund">Refund</option><option value="other">Other</option></select></div>
        <div class="form-group"><label>Amount</label><input type="number" step="0.01" name="amount" required></div>
        <div class="form-group"><label>Date</label><input type="date" name="payment_date" value="<?php echo date('Y-m-d'); ?>" required></div>
        <div class="form-group"><label>Notes</label><input type="text" name="notes"></div>
      </div>
      <div class="form-actions"><button class="btn btn-primary" type="submit">Save payment</button></div>
    </form>
  </div>

  <div class="card">
    <div class="page-header-title"><h1 style="font-size:1.05rem">Payment history</h1></div>
    <div class="table-responsive">
      <table class="table">
        <thead><tr><th>Date</th><th>Type</th><th>Amount</th><th>Notes</th></tr></thead>
        <tbody>
        <?php foreach ($rows as $r): ?>
          <tr>
            <td><?php echo h($r['payment_date']); ?></td>
            <td><?php echo h($r['payment_type']); ?></td>
            <td>€ <?php echo h(number_format((float)$r['amount'], 2)); ?></td>
            <td><?php echo h($r['notes']); ?></td>
          </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
