<?php
/**
 * File Sistem Konfigurasi - Admin Panel (High Contrast Edition)
 * Fitur: Manajemen Multi-Key, Live Status Check, & Desain Rapi
 * Dikembangkan oleh: Sikawarsito, S.Kom
 */

session_start();
include '../config/database.php';

// Proteksi Admin
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') { 
    header("Location: ../auth/login_page.php"); exit; 
}

// Auto Migrate tabel target_urls dan logo
@mysqli_query($conn, "CREATE TABLE IF NOT EXISTS target_urls (
    id INT AUTO_INCREMENT PRIMARY KEY,
    nama_url VARCHAR(255) NOT NULL,
    alamat_url TEXT NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)");

$check_logo = mysqli_query($conn, "SHOW COLUMNS FROM settings LIKE 'logo'");
if (mysqli_num_rows($check_logo) == 0) {
    mysqli_query($conn, "ALTER TABLE settings ADD COLUMN logo VARCHAR(255) DEFAULT NULL");
}

// Fungsi Cek Status Key Dihapus
// PROSES SIMPAN
$msg = "";
if (isset($_POST['save_config'])) {
    $nama_app = mysqli_real_escape_string($conn, $_POST['nama_aplikasi']);
    $pesan    = mysqli_real_escape_string($conn, $_POST['pesan_sambutan']);
    
    $mm = isset($_POST['maintenance_mode']) ? 1 : 0;

    // Handle Upload Logo
    $logo_path = null;
    if (isset($_FILES['logo_upload']) && $_FILES['logo_upload']['error'] == 0) {
        $allowed = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
        $filename = $_FILES['logo_upload']['name'];
        $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
        
        if (in_array($ext, $allowed)) {
            $new_filename = 'logo_' . time() . '.' . $ext;
            $upload_dir = '../uploads/';
            if (!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);
            
            if (move_uploaded_file($_FILES['logo_upload']['tmp_name'], $upload_dir . $new_filename)) {
                $logo_path = 'uploads/' . $new_filename;
            }
        } else {
            $msg = "<div class='alert alert-danger'>Format logo tidak didukung! Gunakan JPG, PNG, GIF, atau WebP.</div>";
        }
    }

    if (empty($msg)) {
        if ($logo_path) {
            $sql = "UPDATE settings SET 
                    nama_aplikasi = '$nama_app', pesan_sambutan = '$pesan',
                    maintenance_mode = '$mm', logo = '$logo_path' WHERE id = 1";
        } else {
            $sql = "UPDATE settings SET 
                    nama_aplikasi = '$nama_app', pesan_sambutan = '$pesan',
                    maintenance_mode = '$mm' WHERE id = 1";
        }

        if (mysqli_query($conn, $sql)) {
            $msg = "<div class='alert alert-success border-0 shadow-sm rounded-3 mb-4 d-flex align-items-center'><i class='bi bi-check-circle-fill fs-4 me-3'></i><div><strong>Berhasil!</strong><br>Konfigurasi sistem telah diperbarui dan disinkronkan.</div></div>";
            
            // Ambil data terbaru untuk update manifest
            $q_latest = mysqli_query($conn, "SELECT nama_aplikasi, logo FROM settings WHERE id = 1");
            if ($row_latest = mysqli_fetch_assoc($q_latest)) {
                $manifest_path = '../manifest.json';
                if (file_exists($manifest_path)) {
                    $manifest_data = json_decode(file_get_contents($manifest_path), true);
                    $manifest_data['name'] = $row_latest['nama_aplikasi'];
                    $manifest_data['short_name'] = $row_latest['nama_aplikasi'];
                    
                    if (!empty($row_latest['logo'])) {
                        $ext = strtolower(pathinfo($row_latest['logo'], PATHINFO_EXTENSION));
                        $mime = in_array($ext, ['jpg','jpeg']) ? 'image/jpeg' : ($ext == 'webp' ? 'image/webp' : ($ext == 'svg' ? 'image/svg+xml' : 'image/png'));
                        $manifest_data['icons'] = [
                            [
                                "src" => $row_latest['logo'],
                                "sizes" => "192x192 512x512",
                                "type" => $mime,
                                "purpose" => "any maskable"
                            ]
                        ];
                    }
                    file_put_contents($manifest_path, json_encode($manifest_data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
                }
            }
        } else {
            $msg = "<div class='alert alert-danger'>Error: " . mysqli_error($conn) . "</div>";
        }
    }
}

// PROSES TAMBAH URL
if (isset($_POST['add_url'])) {
    $nama = mysqli_real_escape_string($conn, $_POST['nama_url']);
    $url  = mysqli_real_escape_string($conn, $_POST['alamat_url']);
    if (!empty($nama) && !empty($url)) {
        mysqli_query($conn, "INSERT INTO target_urls (nama_url, alamat_url) VALUES ('$nama', '$url')");
        $msg = "<div class='alert alert-success border-0 shadow-sm rounded-3 mb-4 d-flex align-items-center'><i class='bi bi-check-circle-fill fs-4 me-3'></i><div><strong>Berhasil!</strong><br>URL Target telah ditambahkan.</div></div>";
    }
}

// PROSES HAPUS URL
if (isset($_GET['delete_url'])) {
    $id_del = (int)$_GET['delete_url'];
    mysqli_query($conn, "DELETE FROM target_urls WHERE id = $id_del");
    header("Location: konfigurasi.php?msg=urldeleted");
    exit;
}

if (isset($_GET['msg']) && $_GET['msg'] == 'urldeleted') {
    $msg = "<div class='alert alert-success border-0 shadow-sm rounded-3 mb-4 d-flex align-items-center'><i class='bi bi-check-circle-fill fs-4 me-3'></i><div><strong>Berhasil!</strong><br>URL Target telah dihapus.</div></div>";
}

// PROSES EDIT URL (FETCH DATA)
$edit_data = null;
if (isset($_GET['edit_url'])) {
    $id_edit = (int)$_GET['edit_url'];
    $res_edit = mysqli_query($conn, "SELECT * FROM target_urls WHERE id = $id_edit");
    $edit_data = mysqli_fetch_assoc($res_edit);
}

// PROSES UPDATE URL
if (isset($_POST['update_url'])) {
    $id_up = (int)$_POST['id_url'];
    $nama  = mysqli_real_escape_string($conn, $_POST['nama_url']);
    $url   = mysqli_real_escape_string($conn, $_POST['alamat_url']);
    if (!empty($nama) && !empty($url)) {
        mysqli_query($conn, "UPDATE target_urls SET nama_url = '$nama', alamat_url = '$url' WHERE id = $id_up");
        $msg = "<div class='alert alert-success border-0 shadow-sm rounded-3 mb-4 d-flex align-items-center'><i class='bi bi-check-circle-fill fs-4 me-3'></i><div><strong>Berhasil!</strong><br>URL Target telah diperbarui.</div></div>";
        // Reset edit mode agar form kembali ke 'Tambah'
        $edit_data = null;
    }
}


$query = mysqli_query($conn, "SELECT * FROM settings WHERE id = 1");
$cfg = mysqli_fetch_assoc($query);
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>System Config | <?= htmlspecialchars($cfg['nama_aplikasi']) ?></title>
    
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
    
    <style>
        :root { 
            --primary-color: #2563eb;
            --bg-color: #f1f5f9;
            --text-dark: #1e293b;
            --card-bg: rgba(255, 255, 255, 0.95);
        }
        body { background-color: var(--bg-color); font-family: 'Plus Jakarta Sans', sans-serif; color: var(--text-dark); }
        
        /* Glass Card Effect */
        .glass-card {
            background: var(--card-bg);
            backdrop-filter: blur(12px);
            border: 1px solid #e2e8f0;
            border-radius: 20px;
            box-shadow: 0 10px 30px -10px rgba(0,0,0,0.1);
            overflow: hidden;
        }

        /* Header Gradient */
        .header-hero { 
            background: linear-gradient(135deg, #2563eb 0%, #1e40af 100%); 
            padding: 35px; 
            text-align: center; 
            color: white; 
        }

        /* Form Sections */
        .section-box {
            background: #fff; 
            border: 1px solid #e2e8f0;
            border-radius: 16px; 
            padding: 25px; 
            margin-bottom: 25px;
            box-shadow: 0 4px 6px -1px rgba(0,0,0,0.02);
            transition: transform 0.2s;
        }
        .section-box:hover {
            border-color: #cbd5e1;
        }

        /* Typography */
        .form-label { 
            font-size: 0.75rem; 
            text-transform: uppercase; 
            font-weight: 700; 
            color: #64748b; 
            letter-spacing: 0.5px; 
            margin-bottom: 8px; 
            display: block;
        }

        /* Inputs - High Contrast Fix */
        .form-control { 
            border-radius: 10px; 
            padding: 12px 15px; 
            border: 1px solid #cbd5e1; 
            font-size: 0.95rem; 
            background-color: #ffffff !important; /* Paksa Putih */
            color: #1e293b !important; /* Paksa Hitam Gelap */
            font-weight: 500;
        }
        .form-control:focus { 
            border-color: var(--primary-color); 
            box-shadow: 0 0 0 4px rgba(37, 99, 235, 0.1); 
            background-color: #fff !important;
        }
        /* Input khusus Model Name */
        .input-highlight {
            border-color: #93c5fd;
            background-color: #eff6ff !important; /* Sedikit biru sangat muda */
            color: #1d4ed8 !important; /* Biru tua teksnya */
            font-weight: 700;
        }

        /* Badges Alignment */
        .label-wrapper {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 8px;
        }
    </style>
</head>
<body class="py-5">

<div class="container">
    <div class="row justify-content-center">
        <div class="col-lg-10 col-xl-9">
            
            <div class="d-flex justify-content-between align-items-center mb-4 px-2">
                <a href="index.php" class="btn btn-white bg-white border shadow-sm text-secondary fw-bold rounded-pill px-4">
                    <i class="bi bi-arrow-left me-2"></i> Kembali
                </a>
                <div class="text-end">
                    <h5 class="fw-bold m-0 text-dark">Control Panel</h5>
                    <div class="badge bg-primary bg-opacity-10 text-primary px-3 py-1 rounded-pill mt-1">Enterprise v4.0</div>
                </div>
            </div>

            <div class="glass-card">
                <div class="header-hero">
                    <i class="bi bi-gear-wide-connected fs-1 mb-2 d-block opacity-75"></i>
                    <h3 class="fw-bold mb-1">Konfigurasi Sistem AI</h3>
                    <p class="opacity-75 mb-0 font-monospace small">MANAGEMENT CONSOLE</p>
                </div>

                <div class="card-body p-4 p-md-5">
                    <?= $msg ?>

                    <form method="POST" enctype="multipart/form-data">
                        
                        <div class="section-box border-start border-4 border-dark">
                            <h6 class="fw-bold text-dark border-bottom pb-3 mb-4 d-flex align-items-center">
                                <span class="bg-dark text-white rounded-circle d-flex align-items-center justify-content-center me-3" style="width:32px; height:32px;"><i class="bi bi-fingerprint"></i></span>
                                Identitas Aplikasi
                            </h6>
                            <div class="row g-4">
                                <div class="col-md-7">
                                    <label class="form-label">Nama Branding</label>
                                    <input type="text" name="nama_aplikasi" class="form-control fw-bold fs-5" value="<?= htmlspecialchars($cfg['nama_aplikasi']) ?>" required>
                                </div>
                                <div class="col-md-5">
                                    <label class="form-label">Mode Maintenance</label>
                                    <div class="form-check form-switch p-0 m-0 border rounded-3 d-flex align-items-center justify-content-between px-3 py-2 bg-light">
                                        <label class="form-check-label small fw-bold text-muted mb-0" for="mm">Blokir Akses Siswa</label>
                                        <input class="form-check-input ms-0" type="checkbox" role="switch" id="mm" name="maintenance_mode" <?= $cfg['maintenance_mode'] ? 'checked' : '' ?> style="transform: scale(1.2);">
                                    </div>
                                </div>
                                <div class="col-md-12">
                                    <label class="form-label">Logo Aplikasi</label>
                                    <div class="d-flex align-items-center gap-3">
                                        <?php if (!empty($cfg['logo']) && file_exists('../' . $cfg['logo'])): ?>
                                            <div class="border rounded p-1 shadow-sm bg-white" style="width: 80px; height: 80px; display:flex; align-items:center; justify-content:center;">
                                                <img src="../<?= $cfg['logo'] ?>" alt="Logo" style="max-width:100%; max-height:100%;">
                                            </div>
                                        <?php else: ?>
                                            <div class="border rounded p-1 shadow-sm bg-light text-muted d-flex align-items-center justify-content-center" style="width: 80px; height: 80px; font-size:2rem;">
                                                <i class="bi bi-image"></i>
                                            </div>
                                        <?php endif; ?>
                                        <div class="flex-grow-1">
                                            <input type="file" name="logo_upload" class="form-control" accept="image/*">
                                            <small class="text-muted d-block mt-1">Biarkan kosong jika tidak ingin mengubah logo. Format: JPG, PNG, WebP (Rekomendasi ukuran kotak/persegi).</small>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-12">
                                    <label class="form-label">Pesan Sambutan (Prompt Awal)</label>
                                    <textarea name="pesan_sambutan" class="form-control text-secondary" rows="2"><?= htmlspecialchars($cfg['pesan_sambutan']) ?></textarea>
                                </div>
                                
                                <!-- YOUTUBE API KEY REMOVED -->
                            </div>
                        </div>

                        <!-- Konfigurasi API Gemini & Groq Dihapus -->

                        <div class="d-grid mt-5">
                            <button type="submit" name="save_config" class="btn btn-dark btn-lg fw-bold rounded-4 py-3 shadow-lg hover-scale">
                                <i class="bi bi-cloud-arrow-up-fill me-2"></i> SIMPAN & UPDATE SISTEM
                            </button>
                        </div>

                    </form>

                    <!-- URL Management Section -->
                    <div class="section-box border-start border-4 border-info mt-5">
                        <h6 class="fw-bold text-dark border-bottom pb-3 mb-4 d-flex align-items-center">
                            <span class="bg-info text-white rounded-circle d-flex align-items-center justify-content-center me-3" style="width:32px; height:32px;"><i class="bi bi-link-45deg"></i></span>
                            Manajemen URL Referensi AI
                        </h6>
                        <p class="text-muted small mb-4">Tambahkan URL website (misal: halaman trending YouTube, portal berita) yang akan dibaca oleh AI saat menjawab pertanyaan pengguna.</p>
                        
                        <form method="POST" class="row g-3 mb-4 align-items-end">
                            <?php if ($edit_data): ?>
                                <input type="hidden" name="id_url" value="<?= $edit_data['id'] ?>">
                            <?php endif; ?>
                            <div class="col-md-4">
                                <label class="form-label text-dark"><?= $edit_data ? 'Edit' : 'Tambah' ?> Nama Web / Topik</label>
                                <input type="text" name="nama_url" class="form-control" placeholder="misal: YouTube Trending" value="<?= $edit_data ? htmlspecialchars($edit_data['nama_url']) : '' ?>" required>
                            </div>
                            <div class="col-md-5">
                                <label class="form-label text-dark"><?= $edit_data ? 'Edit' : 'Tambah' ?> Alamat URL</label>
                                <input type="url" name="alamat_url" class="form-control" placeholder="https://..." value="<?= $edit_data ? htmlspecialchars($edit_data['alamat_url']) : '' ?>" required>
                            </div>
                            <div class="col-md-3">
                                <?php if ($edit_data): ?>
                                    <div class="d-flex gap-2">
                                        <button type="submit" name="update_url" class="btn btn-success flex-grow-1 fw-bold"><i class="bi bi-check-lg"></i> Update</button>
                                        <a href="konfigurasi.php" class="btn btn-outline-secondary fw-bold px-3"><i class="bi bi-x"></i></a>
                                    </div>
                                <?php else: ?>
                                    <button type="submit" name="add_url" class="btn btn-primary w-100 fw-bold"><i class="bi bi-plus-lg"></i> Tambah</button>
                                <?php endif; ?>
                            </div>
                        </form>


                        <div class="table-responsive">
                            <table class="table table-hover border align-middle mb-0">
                                <thead class="table-light">
                                    <tr>
                                        <th width="5%">No</th>
                                        <th width="25%">Nama URL</th>
                                        <th width="55%">Alamat URL</th>
                                        <th width="15%" class="text-center">Aksi</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    $no = 1;
                                    // Use @ to suppress error if table doesn't exist on first load before page refresh
                                    $q_url = @mysqli_query($conn, "SELECT * FROM target_urls ORDER BY id DESC");
                                    if ($q_url && mysqli_num_rows($q_url) > 0) {
                                        while ($row_url = mysqli_fetch_assoc($q_url)) {
                                            echo "<tr>";
                                            echo "<td>{$no}</td>";
                                            echo "<td class='fw-bold'>" . htmlspecialchars($row_url['nama_url']) . "</td>";
                                            echo "<td><a href='" . htmlspecialchars($row_url['alamat_url']) . "' target='_blank' class='text-decoration-none text-truncate d-inline-block' style='max-width:300px;'>" . htmlspecialchars($row_url['alamat_url']) . "</a></td>";
                                            echo "<td class='text-center'>
                                                    <div class='btn-group'>
                                                        <a href='?edit_url={$row_url['id']}' class='btn btn-sm btn-outline-primary' title='Edit'><i class='bi bi-pencil'></i></a>
                                                        <a href='?delete_url={$row_url['id']}' class='btn btn-sm btn-outline-danger' onclick='return confirm(\"Hapus URL ini?\")' title='Hapus'><i class='bi bi-trash'></i></a>
                                                    </div>
                                                  </td>";

                                            echo "</tr>";
                                            $no++;
                                        }
                                    } else {
                                        echo "<tr><td colspan='4' class='text-center text-muted py-4'>Belum ada URL yang ditambahkan.</td></tr>";
                                    }
                                    ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="text-center mt-5 mb-5 text-muted small opacity-50">
                &copy; <?= date('Y') ?> AI Management System • Developed by <b>Sikawarsito, S.Kom</b>
            </div>

        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>