<?php
session_start();
header('Content-Type: application/json; charset=UTF-8');

if (!isset($_SESSION['admin'])) {
  echo json_encode(["success"=>false, "status"=>401, "message"=>"Unauthorized"]);
  exit;
}

require_once '../core/conn.php';

$action = $_POST['action'] ?? '';

function respond($ok, $msg, $data=null, $code=200){
  $out = ["success"=>$ok, "status"=>$code, "message"=>$msg];
  if ($data !== null) $out["data"] = $data;
  echo json_encode($out, JSON_UNESCAPED_UNICODE);
  exit;
}

function clean($v){ return trim((string)$v); }

if ($action === '') respond(false, "Missing action", null, 400);

/* ---------- CREATE ---------- */
if ($action === 'create') {
  $company_name = clean($_POST['company_name'] ?? '');
  $branch       = clean($_POST['branch'] ?? '');
  $name         = clean($_POST['name'] ?? '');
  $username     = clean($_POST['username'] ?? '');
  $email        = clean($_POST['email'] ?? '');
  $phone        = clean($_POST['phone'] ?? '');
  $state        = clean($_POST['state'] ?? '');
  $lga          = clean($_POST['lga'] ?? '');
  $address      = clean($_POST['address'] ?? '');
  $type         = clean($_POST['type'] ?? '');
  $password     = (string)($_POST['password'] ?? '');
  $status       = clean($_POST['status'] ?? '1');

  if ($company_name==='' || $branch==='' || $name==='' || $username==='' || $phone==='' || $password==='' || $type==='') {
    respond(false, "Please fill all required fields.", null, 400);
  }
  if (!preg_match('/^\d{11}$/', $phone)) {
    respond(false, "Phone must be 11 digits.", null, 400);
  }
  if (!in_array($status, ['0','1','2'], true)) $status='1';

  // unique username check
  $chk = $con->prepare("SELECT username FROM users WHERE username=? LIMIT 1");
  $chk->bind_param("s", $username);
  $chk->execute();
  $r = $chk->get_result();
  if ($r && $r->num_rows > 0) {
    $chk->close();
    respond(false, "Username already exists.", null, 409);
  }
  $chk->close();

  $hash = password_hash($password, PASSWORD_BCRYPT);

  $photo = null; // keep null by default
  $stmt = $con->prepare("INSERT INTO users (company_name, branch, name, username, email, phone, password, state, lga, address, photo, type, status)
                         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
  if (!$stmt) respond(false, "Prepare failed: ".$con->error, null, 500);

  $stmt->bind_param(
    "sssssssssssss",
    $company_name, $branch, $name, $username, $email, $phone, $hash, $state, $lga, $address, $photo, $type, $status
  );

  if (!$stmt->execute()) {
    $err = $stmt->error;
    $stmt->close();
    respond(false, "Insert failed: ".$err, null, 500);
  }
  $stmt->close();
  respond(true, "User created successfully.");
}

/* ---------- GET ---------- */
if ($action === 'get') {
  $username = clean($_POST['username'] ?? '');
  if ($username==='') respond(false, "Username required.", null, 400);

  $stmt = $con->prepare("SELECT company_name, branch, name, username, email, phone, state, lga, address, photo, type, status
                         FROM users WHERE username=? LIMIT 1");
  if (!$stmt) respond(false, "Prepare failed: ".$con->error, null, 500);

  $stmt->bind_param("s", $username);
  $stmt->execute();
  $res = $stmt->get_result();
  $u = ($res && $res->num_rows) ? $res->fetch_assoc() : null;
  $stmt->close();

  if (!$u) respond(false, "User not found.", null, 404);
  respond(true, "OK", $u);
}

/* ---------- UPDATE ---------- */
if ($action === 'update') {
  $original = clean($_POST['original_username'] ?? '');
  if ($original==='') respond(false, "Original username required.", null, 400);

  $company_name = clean($_POST['company_name'] ?? '');
  $branch       = clean($_POST['branch'] ?? '');
  $name         = clean($_POST['name'] ?? '');
  $username     = clean($_POST['username'] ?? '');
  $email        = clean($_POST['email'] ?? '');
  $phone        = clean($_POST['phone'] ?? '');
  $type         = clean($_POST['type'] ?? '');
  $status       = clean($_POST['status'] ?? '1');
  $new_password = (string)($_POST['new_password'] ?? '');

  if ($name==='' || $username==='' || $phone==='' || $type==='') {
    respond(false, "Name, Username, Phone and Type are required.", null, 400);
  }
  if (!preg_match('/^\d{11}$/', $phone)) {
    respond(false, "Phone must be 11 digits.", null, 400);
  }
  if (!in_array($status, ['0','1','2'], true)) $status='1';

  // if username changed, ensure unique
  if ($username !== $original) {
    $chk = $con->prepare("SELECT username FROM users WHERE username=? LIMIT 1");
    $chk->bind_param("s", $username);
    $chk->execute();
    $r = $chk->get_result();
    if ($r && $r->num_rows > 0) {
      $chk->close();
      respond(false, "New username already exists.", null, 409);
    }
    $chk->close();
  }

  if ($new_password !== '') {
    $hash = password_hash($new_password, PASSWORD_BCRYPT);
    $stmt = $con->prepare("UPDATE users
                           SET company_name=?, branch=?, name=?, username=?, email=?, phone=?, type=?, status=?, password=?
                           WHERE username=? LIMIT 1");
    if (!$stmt) respond(false, "Prepare failed: ".$con->error, null, 500);
    $stmt->bind_param("ssssssssss", $company_name,$branch,$name,$username,$email,$phone,$type,$status,$hash,$original);
  } else {
    $stmt = $con->prepare("UPDATE users
                           SET company_name=?, branch=?, name=?, username=?, email=?, phone=?, type=?, status=?
                           WHERE username=? LIMIT 1");
    if (!$stmt) respond(false, "Prepare failed: ".$con->error, null, 500);
    $stmt->bind_param("sssssssss", $company_name,$branch,$name,$username,$email,$phone,$type,$status,$original);
  }

  if (!$stmt->execute()) {
    $err = $stmt->error;
    $stmt->close();
    respond(false, "Update failed: ".$err, null, 500);
  }

  if ($stmt->affected_rows < 1) {
    $stmt->close();
    respond(false, "No changes made or user not found.", null, 404);
  }

  $stmt->close();
  respond(true, "User updated successfully.");
}

/* ---------- BAN / UNVERIFY / DELETE ---------- */
$username = clean($_POST['username'] ?? '');
if ($username === '' && in_array($action, ['ban','unverify','delete'], true)) {
  respond(false, "Username required.", null, 400);
}

if ($action === 'ban') {
  $stmt = $con->prepare("UPDATE users SET status='2' WHERE username=? LIMIT 1");
  $stmt->bind_param("s", $username);
  $stmt->execute();
  $ok = $stmt->affected_rows > 0;
  $stmt->close();
  if (!$ok) respond(false, "User not found.", null, 404);
  respond(true, "User banned.");
}

if ($action === 'unverify') {
  $stmt = $con->prepare("UPDATE users SET status='0' WHERE username=? LIMIT 1");
  $stmt->bind_param("s", $username);
  $stmt->execute();
  $ok = $stmt->affected_rows > 0;
  $stmt->close();
  if (!$ok) respond(false, "User not found.", null, 404);
  respond(true, "User unverified.");
}

if ($action === 'delete') {
  $stmt = $con->prepare("DELETE FROM users WHERE username=? LIMIT 1");
  $stmt->bind_param("s", $username);
  $stmt->execute();
  $ok = $stmt->affected_rows > 0;
  $stmt->close();
  if (!$ok) respond(false, "User not found.", null, 404);
  respond(true, "User deleted.");
}

respond(false, "Invalid action.", null, 400);
