<?php
require_once "includes/auth.php";
ensure_manager();
require_once "includes/functions.php";

$id = $_POST['id'];

/* معالجة أرقام الهاتف وتحويلها لـ JSON */
$phones = isset($_POST['phone']) ? $_POST['phone'] : [];
if (!is_array($phones)) {
    $phones = [$phones];
}

$clean_phones = [];
foreach ($phones as $p) {
    $p = trim($p);
    if ($p !== '') {
        $clean_phones[] = $p;
    }
}

$phones_json = json_encode(array_values($clean_phones), JSON_UNESCAPED_UNICODE);

/* تجهيز أسماء اللغات */
$name    = "";
$name_ar = isset($_POST['name_ar']) ? trim($_POST['name_ar']) : null;
$name_en = isset($_POST['name_en']) ? trim($_POST['name_en']) : null;
$name_ku = isset($_POST['name_ku']) ? trim($_POST['name_ku']) : null;

/* الاسم الرئيسي = أول لغة متوفرة */
if ($name_ar)      $name = $name_ar;
elseif ($name_en)  $name = $name_en;
elseif ($name_ku)  $name = $name_ku;
else               $name = ''; // احتياط

/* تحديث البيانات */
$sql = "UPDATE branches SET 
name = ?, 
name_ar = ?, 
name_en = ?, 
name_ku = ?, 
phone = ?, 
map_url = ?, 
menu_mode = ?
WHERE id = ?";

db()->prepare($sql)->execute([
    $name,
    $name_ar,
    $name_en,
    $name_ku,
    $phones_json,
    $_POST['map_url'] ?? null,
    $_POST['menu_mode'] ?? 'shared',
    $id
]);

header("Location: branches.php");
exit;
