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

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

function sess_branch_id(){ return $_SESSION['branch_id'] ?? null; }
function is_admin_user(){ return has_role(['admin','super_admin']); }

function customer_existing_columns($mysqli){
  $cols=[]; $res=$mysqli->query("SHOW COLUMNS FROM customers");
  while($r=$res && $row=$res->fetch_assoc()){ $cols[]=$row['Field']; }
  return $cols;
}

switch ($action) {
  case 'list':
    $q = trim($_GET['q'] ?? '');
    $branch_id = isset($_GET['branch_id']) ? (int)$_GET['branch_id'] : null;
    $where=[]; $types=''; $params=[];
    if ($q !== '') { $where[]='(name LIKE CONCAT("%", ?, "%") OR phone LIKE CONCAT("%", ?, "%") OR email LIKE CONCAT("%", ?, "%"))'; $types.='sss'; $params[]=$q; $params[]=$q; $params[]=$q; }
    if (!is_admin_user()){
      $bid = (int)(sess_branch_id() ?? 0); $where[]='branch_id = ?'; $types.='i'; $params[]=$bid;
    } else if (!empty($branch_id)) { $where[]='branch_id = ?'; $types.='i'; $params[]=$branch_id; }
    $sql = 'SELECT id, name, company_name, phone, email, address, city, state, country, gst_no, branch_id FROM customers';
    if ($where) $sql .= ' WHERE '.implode(' AND ',$where);
    $sql .= ' ORDER BY id DESC';
    if ($where){ $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 'get':
    $id=(int)($_GET['id'] ?? 0);
    $stmt=$mysqli->prepare('SELECT id, name, company_name, phone, email, address, city, state, country, gst_no, branch_id FROM customers WHERE id=?');
    $stmt->bind_param('i',$id); $stmt->execute(); $row=$stmt->get_result()->fetch_assoc();
    if(!$row) json_response(['message'=>'Not found'],404);
    if (!is_admin_user()){
      $bid = (int)(sess_branch_id() ?? 0); if ((int)($row['branch_id'] ?? 0) !== $bid) json_response(['message'=>'Forbidden'],403);
    }
    json_response(['data'=>$row]);
    break;

  case 'create':
    ensure_admin_customer();
    if (!validate_csrf($_POST['csrf'] ?? '')) json_response(['message'=>'Invalid CSRF'], 400);
    $name=trim($_POST['name'] ?? ''); if($name==='') json_response(['message'=>'Name required'],400);
    $available = customer_existing_columns($mysqli);
    $fields_order = ['name','company_name','phone','email','address','city','state','country','gst_no'];
    $cols=[]; $place=[]; $vals=[]; $types='';
    foreach($fields_order as $f){ if (in_array($f,$available,true)) { $cols[]=$f; $place[]='?'; $types.='s'; $vals[] = trim($_POST[$f] ?? ''); } }
    // attach branch_id if schema has it
    if (in_array('branch_id',$available,true)) { $cols[]='branch_id'; $place[]='?'; $types.='i'; $vals[]=(int)(sess_branch_id() ?? 0); }
    if (!in_array('name',$cols,true)) json_response(['message'=>'Schema missing required column: name'],500);
    $sql = 'INSERT INTO customers ('.implode(',',$cols).') VALUES ('.implode(',',$place).')';
    $stmt=$mysqli->prepare($sql);
    $stmt->bind_param($types, ...$vals);
    if(!$stmt->execute()) json_response(['message'=>$stmt->error],500);
    json_response(['message'=>'Created','id'=>$mysqli->insert_id]);
    break;

  case 'update':
    ensure_admin_customer();
    if (!validate_csrf($_POST['csrf'] ?? '')) json_response(['message'=>'Invalid CSRF'], 400);
    $id=(int)($_POST['id'] ?? 0); if(!$id) json_response(['message'=>'Missing id'],400);
    $name=trim($_POST['name'] ?? ''); if($name==='') json_response(['message'=>'Name required'],400);
    $available = customer_existing_columns($mysqli);
    $fields_order = ['name','company_name','phone','email','address','city','state','country','gst_no'];
    $sets=[]; $vals=[]; $types='';
    foreach($fields_order as $f){ if (in_array($f,$available,true) && isset($_POST[$f])) { $sets[] = "$f=?"; $types.='s'; $vals[] = trim($_POST[$f] ?? ''); } }
    if (!$sets) json_response(['message'=>'No fields to update'],400);
    // branch guard for non-admins
    if (!is_admin_user()){
      $cur=$mysqli->query('SELECT branch_id FROM customers WHERE id='.(int)$id)->fetch_assoc(); if(!$cur) json_response(['message'=>'Not found'],404);
      if ((int)($cur['branch_id'] ?? 0) !== (int)(sess_branch_id() ?? 0)) json_response(['message'=>'Forbidden'],403);
    }
    $types.='i'; $vals[]=$id;
    $sql='UPDATE customers SET '.implode(',', $sets).' WHERE id=?';
    $stmt=$mysqli->prepare($sql);
    $stmt->bind_param($types, ...$vals);
    if(!$stmt->execute()) json_response(['message'=>$stmt->error],500);
    json_response(['message'=>'Updated']);
    break;

  case 'delete':
    ensure_admin_customer();
    if (!validate_csrf($_POST['csrf'] ?? '')) json_response(['message'=>'Invalid CSRF'], 400);
    $id=(int)($_POST['id'] ?? 0); if(!$id) json_response(['message'=>'Missing id'],400);
    if (!is_admin_user()){
      $cur=$mysqli->query('SELECT branch_id FROM customers WHERE id='.(int)$id)->fetch_assoc(); if(!$cur) json_response(['message'=>'Not found'],404);
      if ((int)($cur['branch_id'] ?? 0) !== (int)(sess_branch_id() ?? 0)) json_response(['message'=>'Forbidden'],403);
    }
    $stmt=$mysqli->prepare('DELETE FROM customers WHERE id=?');
    $stmt->bind_param('i',$id);
    if(!$stmt->execute()) json_response(['message'=>$stmt->error],500);
    json_response(['message'=>'Deleted']);
    break;

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