<?php
session_start();
require_once 'db.php';

if(!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}
$instansi_id = $_SESSION['instansi_id']; 

$msg = '';

// Handle Form Submissions
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['action']) && $_POST['action'] == 'update_user') {
        $user_id = $_POST['user_id'];
        $username = trim($_POST['username']);
        $password = $_POST['password'];

        if (!empty($password)) {
            $hashed = password_hash($password, PASSWORD_DEFAULT);
            $stmt = $pdo->prepare("UPDATE users SET username = ?, password = ? WHERE id = ? AND instansi_id = ?");
            if ($stmt->execute([$username, $hashed, $user_id, $instansi_id])) {
                $msg = "<div class='alert alert-success'>Akun pengguna berhasil diperbarui (beserta password).</div>";
            }
        } else {
            $stmt = $pdo->prepare("UPDATE users SET username = ? WHERE id = ? AND instansi_id = ?");
            if ($stmt->execute([$username, $user_id, $instansi_id])) {
                $msg = "<div class='alert alert-success'>Username berhasil diperbarui.</div>";
            }
        }
    } elseif (isset($_POST['action']) && $_POST['action'] == 'update_instansi') {
        $logo_path = trim($_POST['logo_path']);
        $keyword_global = trim($_POST['keyword_global']);
        $blacklist = trim($_POST['blacklist'] ?? '');
        $demoted_keywords = trim($_POST['demoted_keywords'] ?? '');
        
        $stmt = $pdo->prepare("UPDATE instansi SET logo_path = ?, keyword_global = ?, blacklist = ?, demoted_keywords = ? WHERE id = ?");
        if ($stmt->execute([$logo_path, $keyword_global, $blacklist, $demoted_keywords, $instansi_id])) {
            
            // Sinkronisasi keyword_global ke instansi_entities sebagai target
            $pdo->prepare("DELETE FROM instansi_entities WHERE instansi_id = ? AND type = 'target'")->execute([$instansi_id]);
            $keywords_array = array_filter(array_map('trim', explode(',', $keyword_global)));
            
            if (!empty($keywords_array)) {
                $stmt_ent = $pdo->prepare("INSERT INTO instansi_entities (instansi_id, entity, type, score) VALUES (?, ?, 'target', 50)");
                foreach ($keywords_array as $kw) {
                    if (!empty($kw)) {
                        $stmt_ent->execute([$instansi_id, $kw]);
                    }
                }
            }

            $msg = "<div class='alert alert-success'>Branding, Keyword, Blacklist & Demoted Keywords berhasil diperbarui.</div>";
        }
    }
}

// Ambil data instansi
$stmt_inst = $pdo->prepare("SELECT * FROM instansi WHERE id = ?");
$stmt_inst->execute([$instansi_id]);
$inst_data = $stmt_inst->fetch(PDO::FETCH_ASSOC);
$nama_instansi = $inst_data['nama_instansi'] ?? "Instansi ID $instansi_id";
$logo_path = !empty($inst_data['logo_path']) ? $inst_data['logo_path'] : '';
$keyword_global = !empty($inst_data['keyword_global']) ? $inst_data['keyword_global'] : '';
$blacklist = !empty($inst_data['blacklist']) ? $inst_data['blacklist'] : 'judi, slot, kasino, togel, porn, pinjol, bokep, judol';
$demoted_keywords = !empty($inst_data['demoted_keywords']) ? $inst_data['demoted_keywords'] : '';

$api_key_ai = $inst_data['api_key_ai'] ?? '';
$ai_agent = $inst_data['ai_agent'] ?? 'Groq';
$ai_model = $inst_data['ai_model'] ?? 'llama3-70b-8192';

// Ambil data user admin instansi ini
$stmt_user = $pdo->prepare("SELECT * FROM users WHERE instansi_id = ? LIMIT 1");
$stmt_user->execute([$instansi_id]);
$user_data = $stmt_user->fetch(PDO::FETCH_ASSOC);

?>
<?php require_once 'layout_header.php'; ?>

        <div class="d-flex flex-wrap justify-content-between align-items-center mb-4 gap-3">
            <h4 class="fw-bold m-0 text-slate-800">Pengaturan Sistem</h4>
            <div>
                <span class="badge bg-primary rounded-pill px-3 py-2" style="font-size: 0.9rem;">
                    <i class="fas fa-building me-1"></i> <?= htmlspecialchars($nama_instansi) ?>
                </span>
            </div>
        </div>

        <?= $msg ?>

        <div class="row g-4">
            <!-- Form Pengaturan Akun -->
            <div class="col-md-6">
                <div class="card card-body">
                    <h5 class="fw-bold mb-4"><i class="fas fa-user-shield text-primary me-2"></i> Pengaturan Akun Admin</h5>
                    <?php if($user_data): ?>
                    <form method="POST">
                        <input type="hidden" name="action" value="update_user">
                        <input type="hidden" name="user_id" value="<?= $user_data['id'] ?>">
                        <div class="mb-3">
                            <label class="form-label fw-bold">Username</label>
                            <input type="text" name="username" class="form-control bg-light" value="<?= htmlspecialchars($user_data['username']) ?>" required>
                        </div>
                        <div class="mb-4">
                            <label class="form-label fw-bold">Password Baru</label>
                            <input type="password" name="password" class="form-control bg-light" placeholder="Kosongkan jika tidak ingin mengubah password">
                        </div>
                        <button type="submit" class="btn btn-primary w-100"><i class="fas fa-save me-2"></i> Simpan Akun</button>
                    </form>
                    <?php else: ?>
                    <div class="alert alert-warning">Data admin instansi tidak ditemukan.</div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Form Branding -->
            <div class="col-md-6">
                <div class="card card-body">
                    <h5 class="fw-bold mb-4"><i class="fas fa-paint-brush text-primary me-2"></i> Branding & Logo</h5>
                    <form method="POST">
                        <input type="hidden" name="action" value="update_instansi">
                        <div class="mb-4">
                            <label class="form-label fw-bold">Keyword Global (Analisa Berita)</label>
                            <input type="text" name="keyword_global" class="form-control bg-light mb-2" value="<?= htmlspecialchars($keyword_global) ?>" placeholder="Contoh: Pemko Banjarbaru, Aditya Mufti">
                            <small class="text-muted">Masukkan keyword utama instansi yang akan dijadikan patokan AI untuk menilai relevansi berita (pisahkan dengan koma).</small>
                        </div>
                        <div class="mb-4">
                            <label class="form-label fw-bold">Kata Kunci Blacklist</label>
                            <input type="text" name="blacklist" class="form-control bg-light mb-2" value="<?= htmlspecialchars($blacklist) ?>" placeholder="Contoh: judi, slot, pinjol">
                            <small class="text-muted">Berita yang mengandung kata-kata ini akan otomatis ditolak/diabaikan saat proses scraping.</small>
                        </div>
                        <div class="mb-4">
                            <label class="form-label fw-bold">Kata Kunci Penurun Skor (Demoted Keywords)</label>
                            <input type="text" name="demoted_keywords" class="form-control bg-light mb-2" value="<?= htmlspecialchars($demoted_keywords) ?>" placeholder="Contoh: banjarmasin, martapura, barabai">
                            <small class="text-muted">Setiap kata ini bernilai -10 poin. Cocok untuk memasukkan nama kota/kabupaten lain agar beritanya turun prioritas (kecuali jika digabungkan dengan kota Anda).</small>
                        </div>
                        <div class="mb-4">
                            <label class="form-label fw-bold">Logo & Favicon (URL Gambar)</label>
                            <input type="url" name="logo_path" class="form-control bg-light mb-2" value="<?= htmlspecialchars($logo_path) ?>" placeholder="https://example.com/logo.png">
                            <small class="text-muted">Masukkan URL Logo (direkomendasikan format PNG transparan). Logo ini juga akan menjadi Favicon web browser Anda.</small>
                        </div>
                        <?php if($logo_path): ?>
                        <div class="mb-4 p-3 bg-light rounded text-center border">
                            <p class="small text-muted mb-2 fw-bold">Preview Logo Saat Ini:</p>
                            <img src="<?= htmlspecialchars($logo_path) ?>" style="max-height: 80px; object-fit:contain;">
                        </div>
                        <?php endif; ?>
                        <button type="submit" class="btn btn-primary w-100"><i class="fas fa-save me-2"></i> Simpan Tampilan</button>
                    </form>
                </div>
            </div>
        </div>

    
    
    <script>
        function toggleSidebar() {
            document.getElementById('sidebar').classList.toggle('show');
            document.getElementById('sidebarOverlay').classList.toggle('show');
        }
    </script>
<?php require_once 'layout_footer.php'; ?>
