<?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';

switch ($action) {
  case 'list': {
    $q = trim($_GET['q'] ?? '');
    $sql = 'SELECT id, name, address, phone, is_active FROM branches';
    if ($q !== '') { $sql .= ' WHERE name LIKE CONCAT("%", ?, "%")'; $stmt=$mysqli->prepare($sql); $stmt->bind_param('s',$q); $stmt->execute(); $res=$stmt->get_result(); }
    else { $res = $mysqli->query($sql); }
    $rows=[]; while($r=$res->fetch_assoc()) $rows[]=$r; json_response(['data'=>$rows]);
    }
    break;
  case 'get': {
    $id=(int)($_GET['id']??0); if(!$id) json_response(['message'=>'ID required'],422);
    $stmt=$mysqli->prepare('SELECT id, name, address, phone, is_active FROM branches WHERE id=?');
    $stmt->bind_param('i',$id); $stmt->execute(); $row=$stmt->get_result()->fetch_assoc();
    json_response(['data'=>$row]);
    }
    break;
  case 'create':
    if (!has_role(['admin','super_admin'])) json_response(['message'=>'Forbidden'], 403);
    if (!validate_csrf($_POST['csrf'] ?? '')) json_response(['message'=>'Invalid CSRF'], 400);
    $name = trim($_POST['name'] ?? ''); if ($name==='') json_response(['message'=>'Name required'],422);
    $stmt=$mysqli->prepare('INSERT INTO branches(name,address,phone,is_active) VALUES (?,?,?,1)');
    $stmt->bind_param('sss', $name, $_POST['address'], $_POST['phone']);
    if(!$stmt->execute()) json_response(['message'=>$stmt->error],400);
    json_response(['id'=>$stmt->insert_id]);
    break;
  case 'update':
    if (!has_role(['admin','super_admin'])) json_response(['message'=>'Forbidden'], 403);
    if (!validate_csrf($_POST['csrf'] ?? '')) json_response(['message'=>'Invalid CSRF'], 400);
    $id=(int)($_POST['id']??0); if(!$id) json_response(['message'=>'ID required'],422);
    $stmt=$mysqli->prepare('UPDATE branches SET name=?, address=?, phone=?, is_active=? WHERE id=?');
    $active = (int)($_POST['is_active']??1);
    $stmt->bind_param('sssii', $_POST['name'], $_POST['address'], $_POST['phone'], $active, $id);
    if(!$stmt->execute()) json_response(['message'=>$stmt->error],400);
    json_response(['ok'=>true]);
    break;
  case 'delete':
    if (!has_role(['admin','super_admin'])) json_response(['message'=>'Forbidden'], 403);
    if (!validate_csrf($_POST['csrf'] ?? '')) json_response(['message'=>'Invalid CSRF'], 400);
    $id=(int)($_POST['id']??0); if(!$id) json_response(['message'=>'ID required'],422);
    if(!$mysqli->query('DELETE FROM branches WHERE id='.(int)$id)) json_response(['message'=>$mysqli->error],400);
    json_response(['ok'=>true]);
    break;
  case 'set_current':
    if (!validate_csrf($_POST['csrf'] ?? '')) json_response(['message'=>'Invalid CSRF'], 400);
    $id=(int)($_POST['id']??0); if(!$id) json_response(['message'=>'ID required'],422);
    // verify branch exists and active
    $stmt=$mysqli->prepare('SELECT id, name, is_active FROM branches WHERE id=?');
    $stmt->bind_param('i',$id); $stmt->execute(); $row=$stmt->get_result()->fetch_assoc();
    if(!$row) json_response(['message'=>'Branch not found'],404);
    if ((int)$row['is_active']!==1) json_response(['message'=>'Branch inactive'],400);
    $_SESSION['branch_id'] = (int)$row['id'];
    $_SESSION['branch_name'] = $row['name'];
    json_response(['ok'=>true, 'branch'=>['id'=>$row['id'], 'name'=>$row['name']]]);
    break;
  default:
    json_response(['message'=>'Invalid action'],400);
}
