<?php
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/db.php';

require_login();
header('Content-Type: application/json');

$mysqli = db();
$action = $_GET['action'] ?? $_POST['action'] ?? 'list';

function ensure_admin() {
  if (!has_role(['admin','super_admin'])) {
    json_response(['message' => 'Forbidden'], 403);
  }
}

switch ($action) {
  case 'list':
    $res = $mysqli->query('SELECT u.id, u.username, u.full_name, u.role, u.is_active, u.branch_id, b.name AS branch_name FROM users u LEFT JOIN branches b ON b.id=u.branch_id ORDER BY u.id DESC');
    $data = [];
    while ($row = $res->fetch_assoc()) { $data[] = $row; }
    json_response(['data' => $data]);
    break;

  case 'get':
    $id = (int)($_GET['id'] ?? 0);
    $stmt = $mysqli->prepare('SELECT u.id, u.username, u.full_name, u.role, u.is_active, u.branch_id, b.name AS branch_name FROM users u LEFT JOIN branches b ON b.id=u.branch_id WHERE u.id = ?');
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $user = $stmt->get_result()->fetch_assoc();
    if (!$user) json_response(['message' => 'Not found'], 404);
    json_response(['data' => $user]);
    break;

  case 'create':
    ensure_admin();
    if (!validate_csrf($_POST['csrf'] ?? '')) json_response(['message' => 'Invalid CSRF'], 400);
    $username = trim($_POST['username'] ?? '');
    $full_name = trim($_POST['full_name'] ?? '');
    $role = $_POST['role'] ?? 'sales_user';
    $is_active = isset($_POST['is_active']) ? 1 : 0;
    $password = $_POST['password'] ?? '';
    // Only require branch for sales_user role
    $branch_id = null;
    if ($role === 'sales_user') {
      $branch_id = ($_POST['branch_id'] ?? '') !== '' ? (int)$_POST['branch_id'] : null;
      if (!$branch_id) json_response(['message' => 'Branch is required for Sales User'], 400);
    }
    if (!$username || !$password) json_response(['message' => 'Username and password required'], 400);
    if (!in_array($role, ROLES, true)) json_response(['message' => 'Invalid role'], 400);

    $hash = password_hash($password, PASSWORD_DEFAULT);
    $stmt = $mysqli->prepare('INSERT INTO users (username, full_name, role, is_active, password_hash, branch_id) VALUES (?,?,?,?,?,?)');
    $stmt->bind_param('sssssi', $username, $full_name, $role, $is_active, $hash, $branch_id);
    if (!$stmt->execute()) json_response(['message' => $stmt->error], 500);
    json_response(['message' => 'Created']);
    break;

  case 'update':
    ensure_admin();
    if (!validate_csrf($_POST['csrf'] ?? '')) json_response(['message' => 'Invalid CSRF'], 400);
    $id = (int)($_POST['id'] ?? 0);
    $username = trim($_POST['username'] ?? '');
    $full_name = trim($_POST['full_name'] ?? '');
    $role = $_POST['role'] ?? 'sales_user';
    $is_active = isset($_POST['is_active']) ? 1 : 0;
    $password = $_POST['password'] ?? '';
    // Only require branch for sales_user role
    $branch_id = null;
    if ($role === 'sales_user') {
      $branch_id = ($_POST['branch_id'] ?? '') !== '' ? (int)$_POST['branch_id'] : null;
      if (!$branch_id) json_response(['message' => 'Branch is required for Sales User'], 400);
    }
    if (!$id || !$username) json_response(['message' => 'Missing fields'], 400);
    if (!in_array($role, ROLES, true)) json_response(['message' => 'Invalid role'], 400);

    if ($password) {
      $hash = password_hash($password, PASSWORD_DEFAULT);
      $stmt = $mysqli->prepare('UPDATE users SET username=?, full_name=?, role=?, is_active=?, password_hash=?, branch_id=? WHERE id=?');
      $stmt->bind_param('sssssii', $username, $full_name, $role, $is_active, $hash, $branch_id, $id);
    } else {
      $stmt = $mysqli->prepare('UPDATE users SET username=?, full_name=?, role=?, is_active=?, branch_id=? WHERE id=?');
      $stmt->bind_param('ssssii', $username, $full_name, $role, $is_active, $branch_id, $id);
    }
    if (!$stmt->execute()) json_response(['message' => $stmt->error], 500);
    json_response(['message' => 'Updated']);
    break;

  case 'delete':
    ensure_admin();
    if (!validate_csrf($_POST['csrf'] ?? '')) json_response(['message' => 'Invalid CSRF'], 400);
    $id = (int)($_POST['id'] ?? 0);
    if (!$id) json_response(['message' => 'Missing id'], 400);
    $stmt = $mysqli->prepare('DELETE FROM users WHERE id = ?');
    $stmt->bind_param('i', $id);
    if (!$stmt->execute()) json_response(['message' => $stmt->error], 500);
    json_response(['message' => 'Deleted']);
    break;

  default:
    json_response(['message' => 'Invalid action'], 400);
}
