<?php
session_start();
require_once '../includes/config.php';

if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
  header("Location: ../auth/login.php");
  exit;
}

$action = $_POST['action'] ?? '';
$id = isset($_POST['id']) ? (int)$_POST['id'] : null;

try {
  if ($action === 'add') {
    $username = trim($_POST['username']);
    $email = trim($_POST['email']);
    $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
    $role = in_array($_POST['role'], ['admin', 'officer', 'controller']) ? $_POST['role'] : 'officer';
    $site_id = !empty($_POST['site_id']) ? $_POST['site_id'] : null;

    // Check for duplicate email
    $check = $pdo->prepare("SELECT COUNT(*) FROM users WHERE email = ?");
    $check->execute([$email]);
    if ($check->fetchColumn() > 0) {
      $_SESSION['error'] = "Email already exists.";
      header("Location: manage_users.php");
      exit;
    }

    $stmt = $pdo->prepare("INSERT INTO users (username, email, password, role, site_id) VALUES (?, ?, ?, ?, ?)");
    $stmt->execute([$username, $email, $password, $role, $site_id]);
    $_SESSION['success'] = "User added successfully.";

  } elseif ($action === 'update' && $id) {
    $username = trim($_POST['username']);
    $email = trim($_POST['email']);
    $role = in_array($_POST['role'], ['admin', 'officer', 'controller']) ? $_POST['role'] : 'officer';
    $site_id = !empty($_POST['site_id']) ? $_POST['site_id'] : null;

    // Check for duplicate email (excluding current user)
    $check = $pdo->prepare("SELECT COUNT(*) FROM users WHERE email = ? AND id != ?");
    $check->execute([$email, $id]);
    if ($check->fetchColumn() > 0) {
      $_SESSION['error'] = "Email already exists for another user.";
      header("Location: manage_users.php");
      exit;
    }

    $stmt = $pdo->prepare("UPDATE users SET username = ?, email = ?, role = ?, site_id = ? WHERE id = ?");
    $stmt->execute([$username, $email, $role, $site_id, $id]);

    // Handle optional password reset
    if (!empty($_POST['password'])) {
      $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
      $updatePass = $pdo->prepare("UPDATE users SET password = ? WHERE id = ?");
      $updatePass->execute([$password, $id]);
    }

    $_SESSION['success'] = "User updated successfully.";

  } elseif ($action === 'delete' && $id) {
    $stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");
    $stmt->execute([$id]);
    $_SESSION['success'] = "User deleted successfully.";
  }

} catch (PDOException $e) {
  $_SESSION['error'] = "Database error: " . $e->getMessage();
}

header("Location: manage_users.php");
exit;
