<?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();
$_lang = gp_lang($pdo);
$projectId = (int)($_GET['project_id'] ?? $_POST['project_id'] ?? 0);
if ($projectId <= 0) die('Missing project_id.');
gp_require_project_edit($pdo, $projectId);
gp_require_perm($pdo, 'perm_invoices');

$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') {
    gp_require_csrf();
    if (isset($_POST['delete_payment_id'])) {
        $delId = (int)$_POST['delete_payment_id'];
        if ($delId > 0) {
            $stmt = $pdo->prepare("DELETE FROM project_payments WHERE id = :id AND project_id = :pid");
            $stmt->execute([':id' => $delId, ':pid' => $projectId]);
            gp_log_action($pdo, 'PAYMENT_DELETE', 'project', $projectId, 'Deleted payment record #' . $delId);
            redirect('/gopools/public/projects/payments.php?project_id=' . $projectId);
        }
    } else {
        $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,
            ]);
            gp_log_action($pdo, 'PAYMENT_ADD', 'project', $projectId, 'Added payment: ' . $amount);
            redirect('/gopools/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';
?>
<?php gp_render_project_menu($pdo, $projectId); ?>

<div class="page-header">
  <div class="page-header-title">
    <h1><?php echo gp_tr($pdo,'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="/gopools/public/projects/edit.php?id=<?php echo (int)$projectId; ?>"><?php echo gp_tr($pdo,'back'); ?></a>
  </div>
</div>

<div class="grid-2">
  <div class="card">
    <div class="page-header-title"><h1 style="font-size:1.05rem"><?php echo $_lang==='el'?'Προσθήκη Πληρωμής':'Add payment'; ?></h1></div>
    <?php if ($errors): ?><div class="alert-danger"><?php echo h(implode(' ', $errors)); ?></div><?php endif; ?>
    <form method="post">
      <?php echo csrf_field(); ?>
      <input type="hidden" name="project_id" value="<?php echo (int)$projectId; ?>">
      <div class="form-grid">
        <div class="form-group"><label><?php echo gp_tr($pdo,'type'); ?></label><select name="payment_type"><option value="deposit"><?php echo $_lang==='el'?'Προκαταβολή':'Deposit'; ?></option><option value="payment"><?php echo gp_tr($pdo,'payments'); ?></option><option value="refund"><?php echo $_lang==='el'?'Επιστροφή':'Refund'; ?></option><option value="other"><?php echo $_lang==='el'?'Άλλο':'Other'; ?></option></select></div>
        <div class="form-group"><label><?php echo gp_tr($pdo,'amount'); ?></label><input type="number" step="0.01" name="amount" required></div>
        <div class="form-group"><label><?php echo gp_tr($pdo,'date'); ?></label><input type="date" name="payment_date" value="<?php echo date('Y-m-d'); ?>" required></div>
        <div class="form-group"><label><?php echo gp_tr($pdo,'notes'); ?></label><input type="text" name="notes"></div>
      </div>
      <div class="form-actions"><button class="btn btn-primary" type="submit"><?php echo gp_tr($pdo,'save'); ?></button></div>
    </form>
  </div>

  <div class="card">
    <div class="page-header-title"><h1 style="font-size:1.05rem"><?php echo $_lang==='el'?'Ιστορικό Πληρωμών':'Payment history'; ?></h1></div>
    <div class="table-responsive">
      <table class="table">
        <thead><tr><th><?php echo gp_tr($pdo,'date'); ?></th><th><?php echo gp_tr($pdo,'type'); ?></th><th><?php echo gp_tr($pdo,'amount'); ?></th><th><?php echo gp_tr($pdo,'notes'); ?></th><th></th></tr></thead>
        <tbody>
        <?php foreach ($rows as $r): ?>
          <tr>
            <td><?php echo h(gp_date((string)$r['payment_date'])); ?></td>
            <td><?php 
              if ($r['payment_type'] === 'deposit') echo $_lang==='el'?'Προκαταβολή':'Deposit';
              elseif ($r['payment_type'] === 'refund') echo $_lang==='el'?'Επιστροφή':'Refund';
              elseif ($r['payment_type'] === 'other') echo $_lang==='el'?'Άλλο':'Other';
              else echo gp_tr($pdo,'payments'); 
            ?></td>
            <td>€ <?php echo h(number_format((float)$r['amount'], 2)); ?></td>
            <td><?php echo h($r['notes']); ?></td>
            <td style="text-align:right; display:flex; justify-content:flex-end; gap:8px;">
              <a href="/gopools/public/projects/payment_receipt.php?id=<?php echo (int)$r['id']; ?>" target="_blank" class="btn btn-sm btn-outline-light">🧾 <?php echo $_lang==='el'?'Απόδειξη':'Receipt'; ?></a>
              <form method="post" style="display:inline;" onsubmit="return confirm('<?php echo $_lang==='el'?'Είστε σίγουροι ότι θέλετε να διαγράψετε αυτή την πληρωμή;':'Are you sure you want to delete this payment?'; ?>');">
                  <?php echo csrf_field(); ?>
                  <input type="hidden" name="project_id" value="<?php echo (int)$projectId; ?>">
                  <input type="hidden" name="delete_payment_id" value="<?php echo (int)$r['id']; ?>">
                  <button type="submit" class="btn btn-sm btn-outline-light" style="color:#ef4444; border-color:rgba(239,68,68,0.2);">🗑</button>
              </form>
            </td>
          </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
