<?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();
$page_title = 'Employee Project Expenses';

$projectId = (int)($_GET['project_id'] ?? $_POST['project_id'] ?? 0);
if ($projectId <= 0) die('Missing project_id.');
gp_require_project_edit($pdo, $projectId);

$stmtProject = $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");
$stmtProject->execute([':id' => $projectId]);
$project = $stmtProject->fetch();
if (!$project) die('Project not found.');

$employees = $pdo->query("SELECT id, full_name FROM employees WHERE active = 1 ORDER BY full_name ASC")->fetchAll();
$ok = ''; $errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $employeeId = (int)($_POST['employee_id'] ?? 0);
    $expenseDate = trim((string)($_POST['expense_date'] ?? ''));
    $expenseType = trim((string)($_POST['expense_type'] ?? ''));
    $amount = (float)($_POST['amount'] ?? 0);
    $notes = trim((string)($_POST['notes'] ?? ''));

    if ($employeeId <= 0) $errors[] = 'Choose employee.';
    if ($expenseDate === '') $errors[] = 'Expense date is required.';
    if ($expenseType === '') $errors[] = 'Expense type is required.';
    if ($amount <= 0) $errors[] = 'Amount must be greater than zero.';

    if (!$errors) {
        $stmt = $pdo->prepare("INSERT INTO employee_project_expenses (employee_id, project_id, expense_date, expense_type, amount, notes) VALUES (:employee_id, :project_id, :expense_date, :expense_type, :amount, :notes)");
        $stmt->execute([
            ':employee_id' => $employeeId,
            ':project_id' => $projectId,
            ':expense_date' => $expenseDate,
            ':expense_type' => $expenseType,
            ':amount' => $amount,
            ':notes' => $notes !== '' ? $notes : null,
        ]);
        $ok = 'Employee expense added.';
    }
}

$stmt = $pdo->prepare("SELECT epe.*, e.full_name FROM employee_project_expenses epe LEFT JOIN employees e ON e.id = epe.employee_id WHERE epe.project_id = :pid ORDER BY epe.expense_date DESC, epe.id DESC");
$stmt->execute([':pid' => $projectId]);
$rows = $stmt->fetchAll();

include __DIR__ . '/../includes/header.php';
?>
<div class="page-header">
  <div class="page-header-title">
    <h1>Employee Project Expenses</h1>
    <span><?php echo h(($project['code'] ?? '') . ' · ' . ($project['title'] ?? '') . ' · ' . ($project['customer_name'] ?? '')); ?></span>
  </div>
</div>

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

<div class="grid-2">
  <div class="card">
    <?php if ($ok): ?><div class="alert-danger" style="background:rgba(22,163,74,.15);color:#166534;border-color:rgba(22,163,74,.25)"><?php echo h($ok); ?></div><?php endif; ?>
    <?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>Employee</label><select name="employee_id"><option value="0">Select employee</option><?php foreach ($employees as $e): ?><option value="<?php echo (int)$e['id']; ?>"><?php echo h($e['full_name']); ?></option><?php endforeach; ?></select></div>
        <div class="form-group"><label>Date</label><input type="date" name="expense_date" value="<?php echo date('Y-m-d'); ?>"></div>
        <div class="form-group"><label>Type</label><input type="text" name="expense_type" placeholder="Fuel / Hotel / Food / Tickets"></div>
        <div class="form-group"><label>Amount</label><input type="number" step="0.01" min="0.01" name="amount"></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">Add expense</button></div>
    </form>
  </div>
  <div class="card">
    <div class="page-header-title"><h1 style="font-size:1.05rem">Expense list</h1><span>Employee expenses linked to this project</span></div>
    <?php if (!$rows): ?><p class="small">No employee expenses yet.</p><?php else: ?>
      <div class="table-responsive">
        <table class="table">
          <thead><tr><th>Date</th><th>Employee</th><th>Type</th><th>Amount</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['full_name']); ?></td>
                <td><?php echo h($r['expense_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>
    <?php endif; ?>
  </div>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
