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

$restaurant_id = $_SESSION['restaurant_id'];

// =========================== GET DATA FOR EDIT ===========================
if(isset($_GET['id'])){
    $id = intval($_GET['id']);
    $row = fetch_one("SELECT * FROM branches WHERE id=? AND restaurant_id=?", [$id, $restaurant_id]);
    if(!$row) die("not found");
    echo json_encode($row);
    exit;
}

// =========================== ADD / EDIT ===========================
$id = $_POST['id'] ?? null;

// معالجة أرقام الهاتف
$phones = $_POST['phone'] ?? [];
$cleanPhones = array_filter(array_map('trim', $phones));
$phonesStr = implode(",", $cleanPhones);

// بيانات النصوص
$data = [
    'name_ar'  => clean($_POST['name_ar']),
    'name_en'  => clean($_POST['name_en'] ?? null),
    'name_ku'  => clean($_POST['name_ku'] ?? null),
    'address'  => clean($_POST['address']),
    'map_url'  => clean($_POST['map_url']),
    'whatsapp' => clean($_POST['whatsapp']),
    'phone'    => $phonesStr,
];

// رفع صورة الخلفية
if(isset($_FILES['cover_image']) && $_FILES['cover_image']['error'] === 0){
    $data['cover_image'] = upload_custom("cover_image", "Branch", $_POST['old_cover_image'] ?? null);
}

// رفع فيديو الخلفية
if(isset($_FILES['cover_video']) && $_FILES['cover_video']['error'] === 0){
    $data['cover_video'] = upload_custom_video_or_image("cover_video", "Branch", $_POST['old_cover_video'] ?? null);
}

// ====================== SQL INSERT OR UPDATE ======================
if($id){
    // تعديل
    update_array("branches", $data, "id=$id");
} else {
    // إضافة
    $data['restaurant_id'] = $restaurant_id;
    $data['active'] = 1;
    insert_array("branches", $data);
}

echo "success";
