<?php
require_once __DIR__ . '/../../app/core/bootstrap.php';
require_once __DIR__ . '/../../app/core/project_permissions.php';
auth_require_login();

$pdo = crm_pdo();
$page_title = 'Users Management';

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

$ok = '';
$errors = [];
$editId = (int)($_GET['edit_id'] ?? 0);

$employees = [];
$partners = [];
$customers = [];

try {
    $employees = $pdo->query("SELECT id, full_name FROM employees WHERE active = 1 ORDER BY full_name ASC")->fetchAll();
} catch (Throwable $e) {}
try {
    $partners = $pdo->query("SELECT id, company_name FROM external_partners WHERE active = 1 ORDER BY company_name ASC")->fetchAll();
} catch (Throwable $e) {}
try {
    $customers = $pdo->query("SELECT id, name FROM customers WHERE active = 1 ORDER BY name ASC")->fetchAll();
} catch (Throwable $e) {}

$form = [
    'id' => 0,
    'username' => '',
    'email' => '',
    'role' => 'employee',
    'employee_id' => 0,
    'external_partner_id' => 0,
    'customer_id' => 0,
    'is_active' => 1,
];

if ($editId > 0) {
    $stmt = $pdo->prepare("SELECT id, username, email, role, employee_id, external_partner_id, customer_id, is_active FROM users WHERE id = :id LIMIT 1");
    $stmt->execute([':id' => $editId]);
    $row = $stmt->fetch();
    if ($row) {
        $form = [
            'id' => (int)$row['id'],
            'username' => (string)$row['username'],
            'email' => (string)$row['email'],
            'role' => (string)$row['role'],
            'employee_id' => (int)($row['employee_id'] ?? 0),
            'external_partner_id' => (int)($row['external_partner_id'] ?? 0),
            'customer_id' => (int)($row['customer_id'] ?? 0),
            'is_active' => (int)($row['is_active'] ?? 0),
        ];
    }
}

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

    if ($action === 'save') {
        $id = (int)($_POST['id'] ?? 0);
        $username = trim((string)($_POST['username'] ?? ''));
        $email = trim((string)($_POST['email'] ?? ''));
        $role = trim((string)($_POST['role'] ?? 'employee'));
        $employeeId = (int)($_POST['employee_id'] ?? 0);
        $partnerId = (int)($_POST['external_partner_id'] ?? 0);
        $customerId = (int)($_POST['customer_id'] ?? 0);
        $password = (string)($_POST['password'] ?? '');
        $isActive = isset($_POST['is_active']) ? 1 : 0;

        $form = [
            'id' => $id,
            'username' => $username,
            'email' => $email,
            'role' => $role,
            'employee_id' => $employeeId,
            'external_partner_id' => $partnerId,
            'customer_id' => $customerId,
            'is_active' => $isActive,
        ];

        if ($username === '') $errors[] = 'Username is required.';
        if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = 'Valid email is required.';
        if (!in_array($role, ['admin', 'manager', 'secretary', 'employee', 'partner', 'customer'], true)) $errors[] = 'Invalid role.';

        if ($id === 0 && strlen($password) < 6) {
            $errors[] = 'Password is required for new user and must be at least 6 characters.';
        }

        if (!$errors) {
            try {
                if ($id > 0) {
                    $stmt = $pdo->prepare("
                        UPDATE users
                        SET username = :username,
                            email = :email,
                            role = :role,
                            employee_id = :employee_id,
                            external_partner_id = :external_partner_id,
                            customer_id = :customer_id,
                            is_active = :is_active
                        WHERE id = :id
                    ");
                    $stmt->execute([
                        ':username' => $username,
                        ':email' => $email,
                        ':role' => $role,
                        ':employee_id' => $employeeId > 0 ? $employeeId : null,
                        ':external_partner_id' => $partnerId > 0 ? $partnerId : null,
                        ':customer_id' => $customerId > 0 ? $customerId : null,
                        ':is_active' => $isActive,
                        ':id' => $id,
                    ]);

                    if ($password !== '') {
                        $stmt = $pdo->prepare("UPDATE users SET password_hash = :password_hash WHERE id = :id");
                        $stmt->execute([
                            ':password_hash' => password_hash($password, PASSWORD_DEFAULT),
                            ':id' => $id,
                        ]);
                    }

                    $ok = 'User updated successfully.';
                } else {
                    $stmt = $pdo->prepare("
                        INSERT INTO users (username, email, password_hash, role, employee_id, external_partner_id, customer_id, is_active)
                        VALUES (:username, :email, :password_hash, :role, :employee_id, :external_partner_id, :customer_id, :is_active)
                    ");
                    $stmt->execute([
                        ':username' => $username,
                        ':email' => $email,
                        ':password_hash' => password_hash($password, PASSWORD_DEFAULT),
                        ':role' => $role,
                        ':employee_id' => $employeeId > 0 ? $employeeId : null,
                        ':external_partner_id' => $partnerId > 0 ? $partnerId : null,
                        ':customer_id' => $customerId > 0 ? $customerId : null,
                        ':is_active' => $isActive,
                    ]);
                    $newId = (int)$pdo->lastInsertId();
                    header('Location: /public/settings/users.php?edit_id=' . $newId . '&saved=1');
                    exit;
                }
            } catch (Throwable $e) {
                $errors[] = 'Save failed: ' . $e->getMessage();
            }
        }
    }

    if ($action === 'toggle_active') {
        $id = (int)($_POST['id'] ?? 0);
        try {
            $stmt = $pdo->prepare("UPDATE users SET is_active = CASE WHEN is_active = 1 THEN 0 ELSE 1 END WHERE id = :id");
            $stmt->execute([':id' => $id]);
            $ok = 'User status updated.';
        } catch (Throwable $e) {
            $errors[] = 'Update failed: ' . $e->getMessage();
        }
    }
}

if (isset($_GET['saved']) && $_GET['saved'] === '1') {
    $ok = 'User created successfully.';
}

$rows = [];
try {
    $rows = $pdo->query("
        SELECT id, username, email, role, employee_id, external_partner_id, customer_id, is_active
        FROM users
        ORDER BY id DESC
    ")->fetchAll();
} catch (Throwable $e) {}

include __DIR__ . '/../includes/header.php';
?>
<div class="page-header">
  <div class="page-header-title">
    <h1>Users Management</h1>
    <span>Admin only</span>
  </div>
</div>

<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"><?php echo $form['id'] > 0 ? 'Edit user' : 'Add user'; ?></h1>
      <span>Manual password control for all users</span>
    </div>

    <form method="post">
      <input type="hidden" name="action" value="save">
      <input type="hidden" name="id" value="<?php echo (int)$form['id']; ?>">

      <div class="form-grid">
        <div class="form-group">
          <label>Username</label>
          <input type="text" name="username" value="<?php echo h($form['username']); ?>">
        </div>

        <div class="form-group">
          <label>Email</label>
          <input type="email" name="email" value="<?php echo h($form['email']); ?>">
        </div>

        <div class="form-group">
          <label>Role</label>
          <select name="role">
            <?php foreach (['admin', 'manager', 'secretary', 'employee', 'partner', 'customer'] as $role): ?>
              <option value="<?php echo h($role); ?>" <?php echo $form['role'] === $role ? 'selected' : ''; ?>><?php echo h($role); ?></option>
            <?php endforeach; ?>
          </select>
        </div>

        <div class="form-group">
          <label>Password <?php echo $form['id'] > 0 ? '(leave blank to keep current)' : ''; ?></label>
          <input type="password" name="password">
        </div>

        <div class="form-group">
          <label>Employee link</label>
          <select name="employee_id">
            <option value="0">-</option>
            <?php foreach ($employees as $e): ?>
              <option value="<?php echo (int)$e['id']; ?>" <?php echo (int)$form['employee_id'] === (int)$e['id'] ? 'selected' : ''; ?>><?php echo h($e['full_name']); ?></option>
            <?php endforeach; ?>
          </select>
        </div>

        <div class="form-group">
          <label>Partner link</label>
          <select name="external_partner_id">
            <option value="0">-</option>
            <?php foreach ($partners as $p): ?>
              <option value="<?php echo (int)$p['id']; ?>" <?php echo (int)$form['external_partner_id'] === (int)$p['id'] ? 'selected' : ''; ?>><?php echo h($p['company_name']); ?></option>
            <?php endforeach; ?>
          </select>
        </div>

        <div class="form-group">
          <label>Customer link</label>
          <select name="customer_id">
            <option value="0">-</option>
            <?php foreach ($customers as $c): ?>
              <option value="<?php echo (int)$c['id']; ?>" <?php echo (int)$form['customer_id'] === (int)$c['id'] ? 'selected' : ''; ?>><?php echo h($c['name']); ?></option>
            <?php endforeach; ?>
          </select>
        </div>

        <div class="form-group">
          <label style="display:flex;align-items:center;gap:8px;margin-top:28px">
            <input type="checkbox" name="is_active" <?php echo (int)$form['is_active'] === 1 ? 'checked' : ''; ?>>
            Active
          </label>
        </div>
      </div>

      <div class="form-actions">
        <button class="btn btn-primary" type="submit"><?php echo $form['id'] > 0 ? 'Save user' : 'Create user'; ?></button>
        <?php if ($form['id'] > 0): ?>
          <a class="btn btn-secondary" href="/public/settings/users.php">New user</a>
        <?php endif; ?>
      </div>
    </form>
  </div>

  <div class="card">
    <div class="page-header-title">
      <h1 style="font-size:1.05rem">Users list</h1>
      <span>All users</span>
    </div>

    <?php if (!$rows): ?>
      <p class="small">No users found.</p>
    <?php else: ?>
      <div class="table-responsive">
        <table class="table">
          <thead>
            <tr>
              <th>ID</th>
              <th>User</th>
              <th>Email</th>
              <th>Role</th>
              <th>Links</th>
              <th>Active</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($rows as $r): ?>
              <tr>
                <td>#<?php echo (int)$r['id']; ?></td>
                <td><?php echo h($r['username']); ?></td>
                <td><?php echo h($r['email']); ?></td>
                <td><?php echo h($r['role']); ?></td>
                <td>
                  <?php
                    $links = [];
                    if (!empty($r['employee_id'])) $links[] = 'Employee #' . (int)$r['employee_id'];
                    if (!empty($r['external_partner_id'])) $links[] = 'Partner #' . (int)$r['external_partner_id'];
                    if (!empty($r['customer_id'])) $links[] = 'Customer #' . (int)$r['customer_id'];
                    echo h(implode(' · ', $links));
                  ?>
                </td>
                <td><?php echo (int)$r['is_active'] === 1 ? 'Yes' : 'No'; ?></td>
                <td>
                  <div class="form-actions" style="margin-top:0">
                    <a class="btn btn-sm btn-outline-light" href="/public/settings/users.php?edit_id=<?php echo (int)$r['id']; ?>">Edit</a>
                    <form method="post" style="display:inline">
                      <input type="hidden" name="action" value="toggle_active">
                      <input type="hidden" name="id" value="<?php echo (int)$r['id']; ?>">
                      <button class="btn btn-sm btn-outline-light" type="submit"><?php echo (int)$r['is_active'] === 1 ? 'Disable' : 'Enable'; ?></button>
                    </form>
                  </div>
                </td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    <?php endif; ?>
  </div>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
