<?php
include("db.php");
header("Content-Type: application/json; charset=utf-8");
mysqli_set_charset($db, "utf8");

// $db  => mysqli connection
// $idPublicUser => current user id
$table = "setting_print";

$method = $_SERVER["REQUEST_METHOD"];

// =====================================
// GET: جلب إعدادات الطباعة للمستخدم
// =====================================
if ($method == "GET") {

    $txt = "SELECT 
                is_name, is_logo, is_address, is_phone, is_mail, msg
            FROM $table
            WHERE id_user = '$idPublicUser'
            LIMIT 1";

    $q = mysqli_query($db, $txt);
    $row = mysqli_fetch_assoc($q);

    echo json_encode([
        "ok" => true,
        "data" => $row ?: null
    ], JSON_UNESCAPED_UNICODE);
    exit;
}


// =====================================
// POST: حفظ / تحديث إعدادات الطباعة
// =====================================
if ($method == "POST") {

    // استلام البيانات (مع defaults)
    $is_name    = isset($_POST["is_name"])    ? (int)$_POST["is_name"]    : 0;
    $is_logo    = isset($_POST["is_logo"])    ? (int)$_POST["is_logo"]    : 0;
    $is_address = isset($_POST["is_address"]) ? (int)$_POST["is_address"] : 0;
    $is_phone   = isset($_POST["is_phone"])   ? (int)$_POST["is_phone"]   : 0;
    $is_mail    = isset($_POST["is_mail"])    ? (int)$_POST["is_mail"]    : 0;

    $msg = trim($_POST["msg"] ?? "");
    $msg = mysqli_real_escape_string($db, $msg);

    // هل فيه record موجود؟
    $check = mysqli_query($db, "SELECT id_setting_print FROM $table WHERE id_user='$idPublicUser' LIMIT 1");

    if (mysqli_num_rows($check) > 0) {

        // UPDATE
        $txt = "
            UPDATE $table SET
                is_name    = '$is_name',
                is_logo    = '$is_logo',
                is_address = '$is_address',
                is_phone   = '$is_phone',
                is_mail    = '$is_mail',
                msg        = '$msg'
            WHERE id_user = '$idPublicUser'
        ";

        mysqli_query($db, $txt);

    } else {

        // INSERT
        $txt = "
            INSERT INTO $table (
                id_user, is_name, is_logo, is_address, is_phone, is_mail, msg, date_add
            ) VALUES (
                '$idPublicUser', '$is_name', '$is_logo', '$is_address', '$is_phone', '$is_mail', '$msg', NOW()
            )
        ";

        mysqli_query($db, $txt);
    }

    echo json_encode([
        "ok" => true,
        "msg" => "تم حفظ إعدادات الطباعة بنجاح"
    ], JSON_UNESCAPED_UNICODE);
    exit;
}


// =====================================
// Method غير مدعوم
// =====================================
echo json_encode(["ok"=>false, "msg"=>"Method Not Allowed"], JSON_UNESCAPED_UNICODE);
exit;
