<?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 Access';

if (!gp_can_manage_project_access($pdo)) {
    http_response_code(403);
    exit('Access denied.');
}

$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.id, p.code, p.title, 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'] ?? 'grant'));
    $userId = (int)($_POST['user_id'] ?? 0);

    if ($userId <= 0) {
        $errors[] = 'Select a secretary/user.';
    } else {
        if ($action === 'grant') {
            $stmt = $pdo->prepare("
                INSERT INTO project_edit_permissions (user_id, project_id, can_edit)
                VALUES (:uid, :pid, 1)
                ON DUPLICATE KEY UPDATE can_edit = VALUES(can_edit)
            ");
            $stmt->execute([
                ':uid' => $userId,
                ':pid' => $projectId,
            ]);
            $ok = 'Project edit access granted.';
        } elseif ($action === 'revoke') {
            $stmt = $pdo->prepare("
                DELETE FROM project_edit_permissions
                WHERE user_id = :uid AND project_id = :pid
            ");
            $stmt->execute([
                ':uid' => $userId,
                ':pid' => $projectId,
            ]);
            $ok = 'Project edit access revoked.';
        }
    }
}

$users = $pdo->query("
    SELECT id, username, email, role
    FROM users
    WHERE role IN ('secretary','manager','admin')
    ORDER BY role ASC, username ASC
")->fetchAll();

$stmt = $pdo->prepare("
    SELECT pep.user_id, pep.can_edit, pep.created_at, u.username, u.email, u.role
    FROM project_edit_permissions pep
    LEFT JOIN users u ON u.id = pep.user_id
    WHERE pep.project_id = :pid
    ORDER BY u.role ASC, u.username ASC
");
$stmt->execute([':pid' => $projectId]);
$grants = $stmt->fetchAll();

include __DIR__ . '/../includes/header.php';
?>
<div class="page-header">
  <div class="page-header-title">
    <h1>Project Access</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">
  <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">Grant edit access</h1>
      <span>Admin / manager can grant project editing to secretary</span>
    </div>

    <form method="post">
      <input type="hidden" name="project_id" value="<?php echo (int)$projectId; ?>">
      <input type="hidden" name="action" value="grant">

      <div class="form-grid">
        <div class="form-group" style="grid-column:1/-1">
          <label>User</label>
          <select name="user_id">
            <option value="0">Select user</option>
            <?php foreach ($users as $u): ?>
              <option value="<?php echo (int)$u['id']; ?>">
                <?php echo h(($u['username'] ?? '') . ' · ' . ($u['role'] ?? '') . (!empty($u['email']) ? ' · ' . $u['email'] : '')); ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>
      </div>

      <div class="form-actions">
        <button class="btn btn-primary" type="submit">Grant access</button>
      </div>
    </form>
  </div>

  <div class="card">
    <div class="page-header-title">
      <h1 style="font-size:1.05rem">Current access list</h1>
      <span>Users with edit permission for this project</span>
    </div>

    <?php if (!$grants): ?>
      <p class="small">No custom edit permissions yet.</p>
    <?php else: ?>
      <div class="table-responsive">
        <table class="table">
          <thead>
            <tr>
              <th>User</th>
              <th>Role</th>
              <th>Email</th>
              <th>Granted</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($grants as $g): ?>
              <tr>
                <td><?php echo h($g['username']); ?></td>
                <td><?php echo h($g['role']); ?></td>
                <td><?php echo h($g['email']); ?></td>
                <td><?php echo h($g['created_at']); ?></td>
                <td>
                  <form method="post" onsubmit="return confirm('Revoke project access?')">
                    <input type="hidden" name="project_id" value="<?php echo (int)$projectId; ?>">
                    <input type="hidden" name="action" value="revoke">
                    <input type="hidden" name="user_id" value="<?php echo (int)$g['user_id']; ?>">
                    <button class="btn btn-sm btn-outline-light" type="submit">Revoke</button>
                  </form>
                </td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    <?php endif; ?>
  </div>
</div>

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