<?php
session_start();
header('Content-Type: application/json');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; }
if (!isset($_SESSION['oms_user'])) { echo json_encode(['status'=>'error','msg'=>'Not authenticated']); exit; }
if ($_SESSION['oms_user']['role'] !== 'admin') { echo json_encode(['status'=>'error','msg'=>'Admin only']); exit; }

$host='database.xhost.co.in'; $db='db_iqpj6ze2cf';
$usr='db_iqpj6ze2cf'; $pass='O*9Mp;%5PPDyv8oD';

function getDB(){
    global $host,$db,$usr,$pass; static $c=null; if($c) return $c;
    $c=new PDO("pgsql:host=$host;port=5432;dbname=$db",$usr,$pass);
    $c->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
    return $c;
}

// Read from $_POST first (URL-encoded), fallback to JSON body
if (!empty($_POST)) {
    $input = $_POST;
} else {
    $raw = file_get_contents('php://input');
    $input = json_decode($raw, true) ?? [];
}

$action = trim($input['action'] ?? $_GET['action'] ?? '');

try {
    $pdo = getDB();
    switch ($action) {

    case 'get_users':
        $rows = $pdo->query("SELECT id,username,name,role,is_active,created_at FROM agent_users ORDER BY role,name")->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode(['status'=>'success','users'=>$rows]);
        break;

    case 'create_user':
        $username = strtolower(trim($input['username'] ?? ''));
        $name     = trim($input['name']     ?? '');
        $role     = trim($input['role']     ?? 'agent');
        $password = trim($input['password'] ?? '');
        if (!$username) { echo json_encode(['status'=>'error','msg'=>'Username required']); exit; }
        if (!$name)     { echo json_encode(['status'=>'error','msg'=>'Name required']); exit; }
        if (!$password) { echo json_encode(['status'=>'error','msg'=>'Password required']); exit; }
        if (strlen($password)<6) { echo json_encode(['status'=>'error','msg'=>'Password min 6 chars']); exit; }
        if (!in_array($role,['admin','team_lead','agent','dispatch','writer'])) $role='agent';
        // Check duplicate
        $chk=$pdo->prepare("SELECT id FROM agent_users WHERE LOWER(username)=LOWER($1)");
        $chk->execute([$username]);
        if ($chk->fetch()) { echo json_encode(['status'=>'error','msg'=>'Username already exists']); exit; }
        // Insert
        $hash=password_hash($password,PASSWORD_DEFAULT);
        $stmt=$pdo->prepare("INSERT INTO agent_users (username,password_hash,name,role,is_active) VALUES ($1,$2,$3,$4,TRUE)");
        $stmt->execute([$username,$hash,$name,$role]);
        echo json_encode(['status'=>'success','msg'=>$name.' added successfully!']);
        break;

    case 'update_user':
        $id=(int)($input['id']??0); $name=trim($input['name']??''); $role=trim($input['role']??'agent');
        $active=($input['is_active']??'1')!=='0';
        $pwd=trim($input['password']??'');
        if (!$id||!$name){echo json_encode(['status'=>'error','msg'=>'ID and name required']);exit;}
        if ($pwd&&strlen($pwd)<6){echo json_encode(['status'=>'error','msg'=>'Password min 6 chars']);exit;}
        if ($pwd) {
            $s=$pdo->prepare("UPDATE agent_users SET name=$1,role=$2,is_active=$3,password_hash=$4 WHERE id=$5");
            $s->execute([$name,$role,$active,password_hash($pwd,PASSWORD_DEFAULT),$id]);
        } else {
            $s=$pdo->prepare("UPDATE agent_users SET name=$1,role=$2,is_active=$3 WHERE id=$4");
            $s->execute([$name,$role,$active,$id]);
        }
        echo json_encode(['status'=>'success','msg'=>'User updated']);
        break;

    case 'reset_password':
        $id=(int)($input['id']??0); $pwd=trim($input['new_password']??'');
        if (!$id||strlen($pwd)<6){echo json_encode(['status'=>'error','msg'=>'Invalid']);exit;}
        $s=$pdo->prepare("UPDATE agent_users SET password_hash=$1 WHERE id=$2");
        $s->execute([password_hash($pwd,PASSWORD_DEFAULT),$id]);
        echo json_encode(['status'=>'success','msg'=>'Password reset']);
        break;

    case 'toggle_active':
        $id=(int)($input['id']??0);
        if (!$id){echo json_encode(['status'=>'error','msg'=>'Invalid']);exit;}
        $s=$pdo->prepare("UPDATE agent_users SET is_active=NOT is_active WHERE id=$1 RETURNING is_active");
        $s->execute([$id]); $row=$s->fetch(PDO::FETCH_ASSOC);
        $act=($row['is_active']==='t'||$row['is_active']===true);
        echo json_encode(['status'=>'success','is_active'=>$act,'msg'=>$act?'Activated':'Deactivated']);
        break;

    case 'delete_user':
        $id=(int)($input['id']??0);
        if (!$id){echo json_encode(['status'=>'error','msg'=>'Invalid']);exit;}
        if ($id===(int)($_SESSION['oms_user']['id']??0)){echo json_encode(['status'=>'error','msg'=>'Cannot delete yourself']);exit;}
        $pdo->prepare("DELETE FROM agent_users WHERE id=$1")->execute([$id]);
        echo json_encode(['status'=>'success','msg'=>'User deleted']);
        break;

    default:
        echo json_encode(['status'=>'error','msg'=>'Unknown: '.$action.' POST:'.json_encode($_POST)]);
    }
} catch(Exception $e) {
    echo json_encode(['status'=>'error','msg'=>$e->getMessage()]);
}
