<?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 = $_REQUEST['action'] ?? 'list';

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

switch ($action) {
  case 'list': {
    ensure_admin_only();
    $branch_id = (int)($_GET['branch_id'] ?? 0);
    if (!$branch_id) json_response(['message'=>'branch_id required'], 422);
    $stmt = $mysqli->prepare('SELECT id, username, full_name, role, is_active FROM users WHERE branch_id=? ORDER BY username');
    $stmt->bind_param('i', $branch_id); $stmt->execute();
    $rows=[]; $res=$stmt->get_result(); while($r=$res->fetch_assoc()) $rows[]=$r;
    json_response(['data'=>$rows]);
    }
    break;

  case 'create': {
    ensure_admin_only(); if (!validate_csrf($_POST['csrf'] ?? '')) json_response(['message'=>'Invalid CSRF'], 400);
    $branch_id = (int)($_POST['branch_id'] ?? 0);
    $username = trim($_POST['username'] ?? '');
    $full_name = trim($_POST['full_name'] ?? '');
    $role = $_POST['role'] ?? 'sales_user';
    $is_active = (int)($_POST['is_active'] ?? 1);
    $password = $_POST['password'] ?? '';
    if (!$branch_id || $username==='' || $password==='') json_response(['message'=>'branch_id, username, password required'],422);
    $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('sssisi', $username, $full_name, $role, $is_active, $hash, $branch_id);
    if(!$stmt->execute()) json_response(['message'=>$stmt->error],500);
    json_response(['id'=>$stmt->insert_id]);
    }
    break;

  case 'update': {
    ensure_admin_only(); if (!validate_csrf($_POST['csrf'] ?? '')) json_response(['message'=>'Invalid CSRF'], 400);
    $id=(int)($_POST['id'] ?? 0); if(!$id) json_response(['message'=>'id required'],422);
    $full_name = trim($_POST['full_name'] ?? '');
    $role = $_POST['role'] ?? 'sales_user';
    $is_active = (int)($_POST['is_active'] ?? 1);
    $stmt=$mysqli->prepare('UPDATE users SET full_name=?, role=?, is_active=? WHERE id=?');
    $stmt->bind_param('ssii', $full_name, $role, $is_active, $id); if(!$stmt->execute()) json_response(['message'=>$stmt->error],500);
    json_response(['ok'=>true]);
    }
    break;

  case 'reset_password': {
    ensure_admin_only(); if (!validate_csrf($_POST['csrf'] ?? '')) json_response(['message'=>'Invalid CSRF'], 400);
    $id=(int)($_POST['id'] ?? 0); $password = $_POST['password'] ?? '';
    if(!$id || $password==='') json_response(['message'=>'id and password required'],422);
    $hash = password_hash($password, PASSWORD_DEFAULT);
    $stmt=$mysqli->prepare('UPDATE users SET password_hash=? WHERE id=?');
    $stmt->bind_param('si', $hash, $id); if(!$stmt->execute()) json_response(['message'=>$stmt->error],500);
    json_response(['ok'=>true]);
    }
    break;

  case 'delete': {
    ensure_admin_only(); if (!validate_csrf($_POST['csrf'] ?? '')) json_response(['message'=>'Invalid CSRF'], 400);
    $id=(int)($_POST['id'] ?? 0); if(!$id) json_response(['message'=>'id required'],422);
    // Prefer soft-delete: set is_active=0
    $stmt=$mysqli->prepare('UPDATE users SET is_active=0 WHERE id=?');
    $stmt->bind_param('i',$id); if(!$stmt->execute()) json_response(['message'=>$stmt->error],500);
    json_response(['ok'=>true]);
    }
    break;

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