<?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 = 'Project Equipment';

$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 = [];
$ok = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = trim((string)($_POST['action'] ?? 'create'));

    if ($action === 'delete') {
        $rowId = (int)($_POST['row_id'] ?? 0);
        $stmt = $pdo->prepare("DELETE FROM project_equipment WHERE id = :id AND project_id = :pid");
        $stmt->execute([':id' => $rowId, ':pid' => $projectId]);
        $ok = 'Equipment item deleted.';
    } else {
        $rowId = (int)($_POST['row_id'] ?? 0);
        $itemName = trim((string)($_POST['item_name'] ?? ''));
        $category = trim((string)($_POST['category'] ?? ''));
        $quantity = (float)($_POST['quantity'] ?? 0);
        $unitCost = trim((string)($_POST['unit_cost'] ?? ''));
        $salePrice = trim((string)($_POST['sale_price'] ?? ''));
        $notes = trim((string)($_POST['notes'] ?? ''));

        if ($itemName === '') $errors[] = 'Item name is required.';
        if ($quantity <= 0) $errors[] = 'Quantity must be greater than zero.';

        $unitCostValue = $unitCost !== '' ? (float)$unitCost : 0.0;
        $lineTotal = round($quantity * $unitCostValue, 2);
        $salePriceValue = $salePrice !== '' ? (float)$salePrice : null;

        if (!$errors) {
            if ($action === 'update' && $rowId > 0) {
                $stmt = $pdo->prepare("UPDATE project_equipment SET item_name = :item_name, category = :category, quantity = :quantity, unit_cost = :unit_cost, line_total = :line_total, sale_price = :sale_price, notes = :notes WHERE id = :id AND project_id = :pid");
                $stmt->execute([
                    ':item_name' => $itemName,
                    ':category' => $category !== '' ? $category : null,
                    ':quantity' => $quantity,
                    ':unit_cost' => $unitCost !== '' ? $unitCostValue : null,
                    ':line_total' => $lineTotal,
                    ':sale_price' => $salePriceValue,
                    ':notes' => $notes !== '' ? $notes : null,
                    ':id' => $rowId,
                    ':pid' => $projectId,
                ]);
                $ok = 'Equipment item updated.';
            } else {
                $stmt = $pdo->prepare("INSERT INTO project_equipment (project_id, item_name, category, quantity, unit_cost, line_total, sale_price, notes) VALUES (:project_id, :item_name, :category, :quantity, :unit_cost, :line_total, :sale_price, :notes)");
                $stmt->execute([
                    ':project_id' => $projectId,
                    ':item_name' => $itemName,
                    ':category' => $category !== '' ? $category : null,
                    ':quantity' => $quantity,
                    ':unit_cost' => $unitCost !== '' ? $unitCostValue : null,
                    ':line_total' => $lineTotal,
                    ':sale_price' => $salePriceValue,
                    ':notes' => $notes !== '' ? $notes : null,
                ]);
                $ok = 'Equipment item added.';
            }
        }
    }
}

$editRowId = (int)($_GET['edit_id'] ?? 0);
$editRow = null;
if ($editRowId > 0) {
    $stmt = $pdo->prepare("SELECT * FROM project_equipment WHERE id = :id AND project_id = :pid LIMIT 1");
    $stmt->execute([':id' => $editRowId, ':pid' => $projectId]);
    $editRow = $stmt->fetch();
}

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

include __DIR__ . '/../includes/header.php';
?>
<div class="page-header">
  <div class="page-header-title">
    <h1>Equipment & Costing</h1>
    <span><?php echo h(($project['code'] ?? '') . ' · ' . ($project['title'] ?? '') . ' · ' . ($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>

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

<div class="grid-2" style="margin-top:14px">
  <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; ?>

    <div class="page-header-title"><h1 style="font-size:1.05rem"><?php echo $editRow ? 'Edit equipment item' : 'Add equipment item'; ?></h1><span>Project equipment only</span></div>

    <form method="post">
      <input type="hidden" name="project_id" value="<?php echo (int)$projectId; ?>">
      <input type="hidden" name="action" value="<?php echo $editRow ? 'update' : 'create'; ?>">
      <input type="hidden" name="row_id" value="<?php echo (int)($editRow['id'] ?? 0); ?>">

      <div class="form-grid">
        <div class="form-group"><label>Item name</label><input type="text" name="item_name" value="<?php echo h($editRow['item_name'] ?? ''); ?>"></div>
        <div class="form-group"><label>Category</label><input type="text" name="category" value="<?php echo h($editRow['category'] ?? ''); ?>"></div>
        <div class="form-group"><label>Quantity</label><input type="number" step="0.01" min="0.01" name="quantity" value="<?php echo h((string)($editRow['quantity'] ?? '1')); ?>"></div>
        <div class="form-group"><label>Unit cost</label><input type="number" step="0.01" min="0" name="unit_cost" value="<?php echo h((string)($editRow['unit_cost'] ?? '')); ?>"></div>
        <div class="form-group"><label>Sale price</label><input type="number" step="0.01" min="0" name="sale_price" value="<?php echo h((string)($editRow['sale_price'] ?? '')); ?>"></div>
        <div class="form-group" style="grid-column:1/-1"><label>Notes</label><textarea name="notes"><?php echo h($editRow['notes'] ?? ''); ?></textarea></div>
      </div>

      <div class="form-actions">
        <button class="btn btn-primary" type="submit"><?php echo $editRow ? 'Save item' : 'Add item'; ?></button>
        <?php if ($editRow): ?>
          <a class="btn btn-secondary" href="/public/projects/equipment.php?project_id=<?php echo (int)$projectId; ?>">Cancel</a>
        <?php endif; ?>
      </div>
    </form>
  </div>

  <div class="card">
    <div class="page-header-title"><h1 style="font-size:1.05rem">Equipment list</h1><span>Only users with project edit access can modify this list</span></div>
    <?php if (!$rows): ?>
      <p class="small">No equipment items yet.</p>
    <?php else: ?>
      <div class="table-responsive">
        <table class="table">
          <thead><tr><th>Item</th><th>Category</th><th>Qty</th><th>Unit cost</th><th>Line total</th><th>Sale price</th><th></th></tr></thead>
          <tbody>
            <?php foreach ($rows as $r): ?>
              <tr>
                <td><?php echo h($r['item_name']); ?></td>
                <td><?php echo h($r['category']); ?></td>
                <td><?php echo h($r['quantity']); ?></td>
                <td>€ <?php echo h(number_format((float)($r['unit_cost'] ?? 0), 2)); ?></td>
                <td>€ <?php echo h(number_format((float)($r['line_total'] ?? 0), 2)); ?></td>
                <td>€ <?php echo h(number_format((float)($r['sale_price'] ?? 0), 2)); ?></td>
                <td>
                  <div class="form-actions" style="margin-top:0">
                    <a class="btn btn-sm btn-outline-light" href="/public/projects/equipment.php?project_id=<?php echo (int)$projectId; ?>&edit_id=<?php echo (int)$r['id']; ?>">Edit</a>
                    <form method="post" onsubmit="return confirm('Delete equipment item?')" style="display:inline">
                      <input type="hidden" name="project_id" value="<?php echo (int)$projectId; ?>">
                      <input type="hidden" name="action" value="delete">
                      <input type="hidden" name="row_id" value="<?php echo (int)$r['id']; ?>">
                      <button class="btn btn-sm btn-outline-light" type="submit">Delete</button>
                    </form>
                  </div>
                </td>
              </tr>
              <tr><td colspan="7" class="small"><?php echo h($r['notes'] ?? ''); ?></td></tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    <?php endif; ?>
  </div>
</div>

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