<?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);
gp_require_perm($pdo, 'perm_expenses');

$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.');

$vehicles = $pdo->query("SELECT id, license_plate, brand, model FROM vehicles WHERE active = 1 ORDER BY license_plate ASC")->fetchAll();
$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    gp_require_csrf();
    $category = trim((string)($_POST['expense_category'] ?? ''));
    $amount = (float)($_POST['amount'] ?? 0);
    $date = trim((string)($_POST['expense_date'] ?? ''));
    $vehicleId = (int)($_POST['vehicle_id'] ?? 0);
    $notes = trim((string)($_POST['notes'] ?? ''));
    if ($amount <= 0) $errors[] = 'Amount must be greater than zero.';
    if ($date === '') $errors[] = 'Expense date is required.';
    if (!$errors) {
        $stmt = $pdo->prepare("INSERT INTO project_expenses (project_id, expense_category, amount, expense_date, vehicle_id, notes) VALUES (:pid,:cat,:amt,:dt,:vid,:notes)");
        $stmt->execute([
            ':pid' => $projectId,
            ':cat' => $category !== '' ? $category : null,
            ':amt' => $amount,
            ':dt' => $date,
            ':vid' => $vehicleId > 0 ? $vehicleId : null,
            ':notes' => $notes !== '' ? $notes : null,
        ]);
        redirect('/gopools/public/projects/expenses.php?project_id=' . $projectId);
    }
}

$stmt = $pdo->prepare("SELECT pe.*, v.license_plate FROM project_expenses pe LEFT JOIN vehicles v ON v.id = pe.vehicle_id WHERE pe.project_id = :pid ORDER BY pe.expense_date DESC, pe.id DESC");
$stmt->execute([':pid' => $projectId]);
$rows = $stmt->fetchAll();

$stmt = $pdo->prepare("SELECT COALESCE(SUM(amount),0) FROM project_expenses WHERE project_id = :pid");
$stmt->execute([':pid' => $projectId]);
$totalExpenses = (float)$stmt->fetchColumn();

$page_title = 'Project expenses';
include __DIR__ . '/../includes/header.php';
?>
<?php gp_render_project_menu($pdo, $projectId); ?>

<div class="page-header">
  <div class="page-header-title">
    <h1>Expenses · <?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; ?>">? ??s? st? ????</a>
  </div>
</div>

<div class="card" style="margin-bottom:14px">

<div class="grid-2">
  <div class="card">
    <div class="page-header-title"><h1 style="font-size:1.05rem">Add expense</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>Category</label><input type="text" name="expense_category" placeholder="Fuel / Materials / Subcontractor"></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="expense_date" value="<?php echo date('Y-m-d'); ?>" required></div>
        <div class="form-group"><label>Vehicle</label><select name="vehicle_id"><option value="0">None</option><?php foreach ($vehicles as $v): ?><option value="<?php echo (int)$v['id']; ?>"><?php echo h($v['license_plate'] . ' · ' . $v['brand'] . ' ' . $v['model']); ?></option><?php endforeach; ?></select></div>
        <div class="form-group" style="grid-column:1/-1"><label>Notes</label><textarea name="notes"></textarea></div>
      </div>
      <div class="form-actions"><button class="btn btn-primary" type="submit">Save expense</button></div>
    </form>
  </div>

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