<?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'] ?? '');
    $wheres=['is_active=1']; $types=''; $params=[];
    // Branch scoping for non-admins
    $cu=current_user();
    if ($cu && !has_role(['admin','super_admin']) && !empty($cu['branch_id'])) { $wheres[]='branch_id=?'; $types.='i'; $params[]=(int)$cu['branch_id']; }
    // Admin branch filter (optional)
    if (has_role(['admin','super_admin'])) {
      $bid = isset($_GET['branch_id']) && $_GET['branch_id']!=='' ? (int)$_GET['branch_id'] : 0;
      if ($bid>0) { $wheres[]='branch_id=?'; $types.='i'; $params[]=$bid; }
    }
    $sql = 'SELECT id, name, notes, is_active, branch_id FROM store_locations';
    if ($wheres) $sql .= ' WHERE ' . implode(' AND ', $wheres);
    if ($q !== '') { $sql .= ($wheres? ' AND':' WHERE') . ' name LIKE CONCAT("%", ?, "%")'; $types.='s'; $params[]=$q; }
    if ($types){ $stmt=$mysqli->prepare($sql); $stmt->bind_param($types, ...$params); $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 '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);
    $branch_id = isset($_POST['branch_id']) && $_POST['branch_id']!=='' ? (int)$_POST['branch_id'] : null;
    $stmt=$mysqli->prepare('INSERT INTO store_locations(name,notes,is_active,branch_id) VALUES (?,?,1,?)');
    $stmt->bind_param('ssi', $name, $_POST['notes'], $branch_id);
    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);
    $active = (int)($_POST['is_active']??1);
    $branch_id = isset($_POST['branch_id']) && $_POST['branch_id']!=='' ? (int)$_POST['branch_id'] : null;
    $stmt=$mysqli->prepare('UPDATE store_locations SET name=?, notes=?, is_active=?, branch_id=? WHERE id=?');
    $stmt->bind_param('ssiii', $_POST['name'], $_POST['notes'], $active, $branch_id, $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 store_locations WHERE id='.(int)$id)) json_response(['message'=>$mysqli->error],400);
    json_response(['ok'=>true]);
    break;
  default:
    json_response(['message'=>'Invalid action'],400);
}
