<?php
session_start();
include("include/conn.php");
include("include/function.php");
$login = cekSession();
if ($login != 1) {
    redirect("login.php");
}

// Fetch existing settings data
$query = "SELECT * FROM settings WHERE user_id = '1' LIMIT 1"; // Assuming settings are for a global admin user_id 1
$result = mysqli_query($conn, $query);
$settings = mysqli_fetch_assoc($result);

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $bname = mysqli_real_escape_string($conn, $_POST['bname']);
    $logourl = mysqli_real_escape_string($conn, $_POST['logourl']);
    $number = mysqli_real_escape_string($conn, $_POST['number']);
    $amount = mysqli_real_escape_string($conn, $_POST['amount']);
    $apitoken = mysqli_real_escape_string($conn, $_POST['apitoken']);
    $apiurl = mysqli_real_escape_string($conn, $_POST['apiurl']);
    $cstapiurl = mysqli_real_escape_string($conn, $_POST['cstapiurl']);

    if ($settings) {
        // Update existing settings
        $sql = "UPDATE settings SET 
                brand_name = '$bname', logo_url = '$logourl', number = '$number', 
                amount = '$amount', api_token = '$apitoken', api_url = '$apiurl', 
                checkst_apiurl = '$cstapiurl'
                WHERE user_id = '1'";
    } else {
        // Insert new settings
        $sql = "INSERT INTO settings (user_id, brand_name, logo_url, number, amount, api_token, api_url, checkst_apiurl) 
                VALUES ('1', '$bname', '$logourl', '$number', '$amount', '$apitoken', '$apiurl', '$cstapiurl')";
    }
    
    if (mysqli_query($conn, $sql)) {
        $_SESSION['notification'] = ['type' => 'success', 'message' => '¡Configuración guardada exitosamente!'];
    } else {
        $_SESSION['notification'] = ['type' => 'error', 'message' => 'Error al guardar la configuración: ' . mysqli_error($conn)];
    }
    header("Location: site_settings.php");
    exit();
}
?>
<!DOCTYPE html>
<html class="loading" lang="es" data-textdirection="ltr">

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
    <title id="title"><?= $brandName ?> | Ajustes del Sitio</title>
    <link rel="apple-touch-icon" href="assets/images/ico/apple-icon-120.png">
    <link rel="shortcut icon" type="image/x-icon" href="assets/images/ico/favicon.ico">
    <link href="https://fonts.googleapis.com/css?family=Muli:300,300i,400,400i,600,600i,700,700i%7CComfortaa:300,400,700" rel="stylesheet">
    <link href="https://maxcdn.icons8.com/fonts/line-awesome/1.1/css/line-awesome.min.css" rel="stylesheet">
    
    <link rel="stylesheet" type="text/css" href="assets/css/vendors.css">
    <link rel="stylesheet" type="text/css" href="assets/css/app-lite.css">
    <link rel="stylesheet" type="text/css" href="assets/css/core/menu/menu-types/vertical-menu.css">
    <link rel="stylesheet" type="text/css" href="assets/css/core/colors/palette-gradient.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@10/dist/sweetalert2.min.css">

    <style>
        .content-wrapper { background-color: #f3f4f6; }
        .card {
            border: none;
            border-radius: 12px;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1);
        }
        .card-header {
            background-color: transparent;
            border-bottom: 1px solid #e5e7eb;
            padding: 1.5rem;
        }
        .card-title { font-weight: 600; color: #1f2937; }
        .form-control {
            border-radius: 8px;
            border: 1px solid #d1d5db;
            padding: 0.75rem 1rem;
            transition: border-color .15s ease-in-out,box-shadow .15s ease-in-out;
        }
        .form-control:focus {
            color: #495057;
            background-color: #fff;
            border-color: #4f46e5;
            outline: 0;
            box-shadow: 0 0 0 0.2rem rgb(79 70 229 / 25%);
        }
        .btn-primary {
            color: #fff;
            background-color: #4f46e5;
            border-color: #4f46e5;
            border-radius: 8px;
            padding: 0.75rem 1.5rem;
            font-weight: 600;
        }
    </style>
</head>

<body class="vertical-layout vertical-menu 2-columns menu-expanded fixed-navbar" data-open="click" data-menu="vertical-menu" data-color="bg-gradient-x-purple-blue" data-col="2-columns">
    <?php include("include/header.php"); ?>
    <?php include("include/sidebar.php"); ?>

    <div class="app-content content">
        <div class="content-wrapper">
            <div class="content-wrapper-before" style="background:none;"></div>
            <div class="content-header row">
                <div class="content-header-left col-md-4 col-12 mb-2">
                    <h3 class="content-header-title" style="color: #1f2937; font-weight: 700;">Ajustes del Sitio</h3>
                </div>
                <div class="content-header-right col-md-8 col-12">
                    <div class="breadcrumbs-top float-md-right">
                        <div class="breadcrumb-wrapper mr-1">
                            <ol class="breadcrumb">
                                <li class="breadcrumb-item"><a href="index.php">Inicio</a></li>
                                <li class="breadcrumb-item active">Ajustes del Sitio</li>
                            </ol>
                        </div>
                    </div>
                </div>
            </div>
            <div class="content-body">
                <div class="row justify-content-center">
                    <div class="col-md-8">
                        <div class="card">
                            <div class="card-header">
                                <h4 class="card-title">Configuración General</h4>
                            </div>
                            <div class="card-body">
                                <form method="POST" action="">
                                    <div class="form-group">
                                        <label for="bname" class="font-weight-bold">Nombre de la Marca</label>
                                        <input type="text" class="form-control" id="bname" name="bname" value="<?= htmlspecialchars($settings['brand_name'] ?? '') ?>" required>
                                    </div>
                                    <div class="form-group">
                                        <label for="logourl" class="font-weight-bold">URL del Logo</label>
                                        <input type="text" class="form-control" id="logourl" name="logourl" value="<?= htmlspecialchars($settings['logo_url'] ?? '') ?>" required>
                                    </div>
                                    <div class="form-group">
                                        <label for="number" class="font-weight-bold">Número de Soporte</label>
                                        <input type="number" class="form-control" id="number" name="number" value="<?= htmlspecialchars($settings['number'] ?? '') ?>" required>
                                    </div>
                                    <div class="form-group">
                                        <label for="amount" class="font-weight-bold">Monto de Compra</label>
                                        <input type="number" class="form-control" id="amount" name="amount" value="<?= htmlspecialchars($settings['amount'] ?? '') ?>" required>
                                    </div>
                                    <hr class="my-4">
                                    <h5 class="font-weight-bold mb-3">Configuración de API</h5>
                                    <div class="form-group">
                                        <label for="apitoken" class="font-weight-bold">Token de API</label>
                                        <input type="text" class="form-control" id="apitoken" name="apitoken" value="<?= htmlspecialchars($settings['api_token'] ?? '') ?>" required>
                                    </div>
                                    <div class="form-group">
                                        <label for="apiurl" class="font-weight-bold">URL de API</label>
                                        <input type="text" class="form-control" id="apiurl" name="apiurl" value="<?= htmlspecialchars($settings['api_url'] ?? '') ?>" required>
                                    </div>
                                    <div class="form-group">
                                        <label for="cstapiurl" class="font-weight-bold">URL de API (Verificar Estado)</label>
                                        <input type="text" class="form-control" id="cstapiurl" name="cstapiurl" value="<?= htmlspecialchars($settings['checkst_apiurl'] ?? '') ?>" required>
                                    </div>
                                    <button type="submit" class="btn btn-primary mt-2">Guardar Cambios</button>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <?php include("include/footer.php"); ?>
    
    <script src="assets/vendors/js/vendors.min.js" type="text/javascript"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@10"></script>
    <script src="assets/js/core/app-menu-lite.js" type="text/javascript"></script>
    <script src="assets/js/core/app-lite.js" type="text/javascript"></script>

    <script>
    $(document).ready(function() {
        <?php
        if (isset($_SESSION['notification'])) {
            $notification = $_SESSION['notification'];
            $title = ($notification['type'] == 'success') ? '¡Éxito!' : 'Error';
            echo "Swal.fire({
                icon: '{$notification['type']}',
                title: '{$title}',
                text: '{$notification['message']}',
                confirmButtonColor: '#4f46e5'
            });";
            unset($_SESSION['notification']);
        }
        ?>
    });
    </script>
</body>
</html>

