<?php
require_once __DIR__ . '/../../app/core/bootstrap.php';
require_once __DIR__ . '/../../app/core/project_permissions.php';
require_once __DIR__ . '/../../app/core/access_guards.php';
auth_require_login();
$pdo = crm_pdo();
gp_require_staff_access($pdo);

$page_title = 'Project cost report';

$projects = $pdo->query("SELECT id, code, title FROM projects ORDER BY code ASC")->fetchAll();
$projectId = (int)($_GET['project_id'] ?? 0);

$summary = null;
$laborRows = [];
$expenseRows = [];
$paymentRows = [];
$serviceRows = [];

if ($projectId > 0) {
    $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");
    $stmt->execute([':id' => $projectId]);
    $summary = $stmt->fetch();

    $stmt = $pdo->prepare("
        SELECT ws.*, e.full_name, COALESCE(e.hourly_rate,0) AS hourly_rate
        FROM work_sessions ws
        LEFT JOIN employees e ON e.id = ws.employee_id
        WHERE ws.project_id = :pid
          AND ws.duration_minutes IS NOT NULL
        ORDER BY ws.start_time DESC
    ");
    $stmt->execute([':pid' => $projectId]);
    $laborRows = $stmt->fetchAll();

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

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

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

$totalLabor = 0.0;
$totalLaborHours = 0.0;
foreach ($laborRows as $r) {
    $hours = ((int)$r['duration_minutes']) / 60;
    $totalLaborHours += $hours;
    $totalLabor += ((float)$r['hourly_rate']) * $hours;
}

$totalExpenses = 0.0;
foreach ($expenseRows as $r) $totalExpenses += (float)$r['amount'];

$totalPayments = 0.0;
foreach ($paymentRows as $r) {
    if (in_array($r['payment_type'], ['deposit','payment'], true)) $totalPayments += (float)$r['amount'];
}

$budget = (float)($summary['budget'] ?? 0);
$profit = $budget - ($totalLabor + $totalExpenses);

include __DIR__ . '/../includes/header.php';
?>
<div class="page-header">
  <div class="page-header-title">
    <h1>Project cost report</h1>
    <span>Budget, labor, expenses, payments</span>
  </div>
</div>

<div class="card" style="margin-bottom:14px">
  <form method="get">
    <div class="form-grid">
      <div class="form-group">
        <label>Project</label>
        <select name="project_id">
          <option value="0">Select project</option>
          <?php foreach ($projects as $p): ?>
            <option value="<?php echo (int)$p['id']; ?>" <?php echo $projectId === (int)$p['id'] ? 'selected' : ''; ?>>
              <?php echo h($p['code'] . ' · ' . $p['title']); ?>
            </option>
          <?php endforeach; ?>
        </select>
      </div>
    </div>
    <div class="form-actions">
      <button class="btn btn-primary" type="submit">Load</button>
      <button class="btn btn-secondary" type="button" onclick="window.print()">Print</button>
    </div>
  </form>
</div>

<?php if ($summary): ?>
  <div class="grid-4" style="margin-bottom:14px">
    <div class="card"><div class="small">Budget</div><div style="font-size:1.6rem;font-weight:700">€ <?php echo h(number_format($budget, 2)); ?></div></div>
    <div class="card"><div class="small">Labor cost</div><div style="font-size:1.6rem;font-weight:700">€ <?php echo h(number_format($totalLabor, 2)); ?></div><div class="small"><?php echo h(number_format($totalLaborHours, 2)); ?> h</div></div>
    <div class="card"><div class="small">Other expenses</div><div style="font-size:1.6rem;font-weight:700">€ <?php echo h(number_format($totalExpenses, 2)); ?></div></div>
    <div class="card"><div class="small">Payments received</div><div style="font-size:1.6rem;font-weight:700">€ <?php echo h(number_format($totalPayments, 2)); ?></div></div>
  </div>

  <div class="card" style="margin-bottom:14px">
    <div class="small">Estimated project result</div>
    <div style="font-size:2rem;font-weight:700">€ <?php echo h(number_format($profit, 2)); ?></div>
    <div class="small"><?php echo h($summary['code'] . ' · ' . $summary['title'] . ' · ' . ($summary['customer_name'] ?? '')); ?></div>
  </div>

  <div class="grid-2">
    <div class="card">
      <div class="page-header-title"><h1 style="font-size:1rem">Labor entries</h1></div>
      <div class="table-responsive">
        <table class="table">
          <thead><tr><th>Employee</th><th>Date</th><th>Hours</th><th>Rate</th><th>Cost</th></tr></thead>
          <tbody>
          <?php foreach ($laborRows as $r): ?>
            <?php $hours = ((int)$r['duration_minutes']) / 60; $cost = $hours * (float)$r['hourly_rate']; ?>
            <tr>
              <td><?php echo h($r['full_name']); ?></td>
              <td><?php echo h(substr((string)$r['start_time'], 0, 10)); ?></td>
              <td><?php echo h(number_format($hours, 2)); ?></td>
              <td>€ <?php echo h(number_format((float)$r['hourly_rate'], 2)); ?></td>
              <td>€ <?php echo h(number_format($cost, 2)); ?></td>
            </tr>
          <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>

    <div class="card">
      <div class="page-header-title"><h1 style="font-size:1rem">Expense entries</h1></div>
      <div class="table-responsive">
        <table class="table">
          <thead><tr><th>Date</th><th>Category</th><th>Amount</th><th>Notes</th></tr></thead>
          <tbody>
          <?php foreach ($expenseRows 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['notes']); ?></td>
            </tr>
          <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
<?php endif; ?>

<style>
@media print {
  .navbar-gp, form, .form-actions, .page-header-actions { display:none !important; }
  body { background:#fff !important; color:#000 !important; }
  .card { box-shadow:none !important; }
}
</style>

<?php include __DIR__ . '/../includes/footer.php'; ?>
