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

// Cek autentikasi dan otorisasi superadmin
if(!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'superadmin') {
    header("Location: login.php");
    exit;
}

$msg = '';

// Handle CRUD Instansi
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['action'])) {
        if ($_POST['action'] == 'add') {
            $nama = $_POST['nama_instansi'];
            $keyword = $_POST['keyword_global'];
            $api_key = $_POST['api_key_ai'];
            $ai_agent = $_POST['ai_agent'];
            $ai_model = $_POST['ai_model'];
            $username = $_POST['username'];
            $password = $_POST['password'];
            $email = $_POST['email'] ?? '';

            $username_pimpinan = $_POST['username_pimpinan'] ?? '';
            $password_pimpinan = $_POST['password_pimpinan'] ?? '';

            $pdo->beginTransaction();
            try {
                $stmt = $pdo->prepare("INSERT INTO instansi (nama_instansi, keyword_global, api_key_ai, ai_agent, ai_model, status) VALUES (?, ?, ?, ?, ?, 'aktif')");
                $stmt->execute([$nama, $keyword, $api_key, $ai_agent, $ai_model]);
                $new_instansi_id = $pdo->lastInsertId();

                $hash = password_hash($password, PASSWORD_DEFAULT);
                $stmt_user = $pdo->prepare("INSERT INTO users (username, password, role, instansi_id, email) VALUES (?, ?, 'admin_instansi', ?, ?)");
                $stmt_user->execute([$username, $hash, $new_instansi_id, $email]);

                if (!empty($username_pimpinan) && !empty($password_pimpinan)) {
                    $hash_pim = password_hash($password_pimpinan, PASSWORD_DEFAULT);
                    $stmt_pim = $pdo->prepare("INSERT INTO users (username, password, role, instansi_id) VALUES (?, ?, 'pimpinan', ?)");
                    $stmt_pim->execute([$username_pimpinan, $hash_pim, $new_instansi_id]);
                }

                $pdo->commit();
                $msg = "<div class='alert alert-success'>Instansi beserta Akun berhasil dibuat!</div>";
            } catch (Exception $e) {
                $pdo->rollBack();
                $msg = "<div class='alert alert-danger'>Gagal menambahkan instansi: " . $e->getMessage() . "</div>";
            }
        } elseif ($_POST['action'] == 'edit') {
            $id = $_POST['id'];
            $nama = $_POST['nama_instansi'];
            $keyword = $_POST['keyword_global'];
            $api_key = $_POST['api_key_ai'];
            $ai_agent = $_POST['ai_agent'];
            $ai_model = $_POST['ai_model'];
            $email = $_POST['email'] ?? '';

            $username_pimpinan = $_POST['username_pimpinan'] ?? '';
            $password_pimpinan = $_POST['password_pimpinan'] ?? '';

            $stmt = $pdo->prepare("UPDATE instansi SET nama_instansi = ?, keyword_global = ?, api_key_ai = ?, ai_agent = ?, ai_model = ? WHERE id = ?");
            if ($stmt->execute([$nama, $keyword, $api_key, $ai_agent, $ai_model, $id])) {
                // Update password admin jika diisi
                if(!empty($_POST['password'])) {
                    $hash = password_hash($_POST['password'], PASSWORD_DEFAULT);
                    $stmt_pw = $pdo->prepare("UPDATE users SET password = ? WHERE instansi_id = ? AND role = 'admin_instansi'");
                    $stmt_pw->execute([$hash, $id]);
                }
                
                // Update email Google login
                $stmt_email = $pdo->prepare("UPDATE users SET email = ? WHERE instansi_id = ? AND role = 'admin_instansi'");
                $stmt_email->execute([$email, $id]);

                // Handle pimpinan
                if (!empty($username_pimpinan)) {
                    $stmt_cek = $pdo->prepare("SELECT id FROM users WHERE instansi_id = ? AND role = 'pimpinan'");
                    $stmt_cek->execute([$id]);
                    if ($stmt_cek->rowCount() > 0) {
                        // Update
                        if (!empty($password_pimpinan)) {
                            $hash_pim = password_hash($password_pimpinan, PASSWORD_DEFAULT);
                            $stmt_up_pim = $pdo->prepare("UPDATE users SET username = ?, password = ? WHERE instansi_id = ? AND role = 'pimpinan'");
                            $stmt_up_pim->execute([$username_pimpinan, $hash_pim, $id]);
                        } else {
                            $stmt_up_pim = $pdo->prepare("UPDATE users SET username = ? WHERE instansi_id = ? AND role = 'pimpinan'");
                            $stmt_up_pim->execute([$username_pimpinan, $id]);
                        }
                    } else {
                        // Insert
                        if (!empty($password_pimpinan)) {
                            $hash_pim = password_hash($password_pimpinan, PASSWORD_DEFAULT);
                            $stmt_ins_pim = $pdo->prepare("INSERT INTO users (username, password, role, instansi_id) VALUES (?, ?, 'pimpinan', ?)");
                            $stmt_ins_pim->execute([$username_pimpinan, $hash_pim, $id]);
                        }
                    }
                }
                
                $msg = "<div class='alert alert-success'>Data Instansi berhasil diperbarui!</div>";
            }
        } elseif ($_POST['action'] == 'delete') {
            $id = $_POST['id'];
            $pdo->beginTransaction();
            try {
                $pdo->prepare("DELETE FROM users WHERE instansi_id = ?")->execute([$id]);
                $pdo->prepare("DELETE FROM instansi WHERE id = ?")->execute([$id]);
                $pdo->commit();
                $msg = "<div class='alert alert-success'>Instansi dan seluruh akun terkait berhasil dihapus!</div>";
            } catch (Exception $e) {
                $pdo->rollBack();
                $msg = "<div class='alert alert-danger'>Gagal menghapus instansi.</div>";
            }
        } elseif ($_POST['action'] == 'toggle_status') {
            $id = $_POST['id'];
            $current_status = $_POST['current_status'];
            $new_status = ($current_status == 'aktif') ? 'suspend' : 'aktif';
            
            $stmt = $pdo->prepare("UPDATE instansi SET status = ? WHERE id = ?");
            if ($stmt->execute([$new_status, $id])) {
                $status_msg = $new_status == 'aktif' ? 'diaktifkan' : 'disuspend (cron & login dimatikan)';
                $msg = "<div class='alert alert-success'>Status Instansi berhasil $status_msg!</div>";
            } else {
                $msg = "<div class='alert alert-danger'>Gagal mengubah status instansi.</div>";
            }
        }
    }
}

// Ambil data instansi dan usernamenya
$query = "SELECT i.*, u.username, u.email, (SELECT username FROM users WHERE instansi_id = i.id AND role = 'pimpinan' LIMIT 1) as username_pimpinan FROM instansi i LEFT JOIN users u ON i.id = u.instansi_id AND u.role = 'admin_instansi' ORDER BY i.id DESC";
$instansi_list = $pdo->query($query)->fetchAll(PDO::FETCH_ASSOC);

?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>MonitorDaerah - Superadmin</title>
    <!-- plugins:css -->
    <link rel="stylesheet" href="assets_skydash/vendors/feather/feather.css">
    <link rel="stylesheet" href="assets_skydash/vendors/ti-icons/css/themify-icons.css">
    <link rel="stylesheet" href="assets_skydash/vendors/css/vendor.bundle.base.css">
    <link rel="stylesheet" href="assets_skydash/vendors/font-awesome/css/font-awesome.min.css">
    <!-- inject:css -->
    <link rel="stylesheet" href="assets_skydash/css/style.css">
    <!-- endinject -->
    <link rel="shortcut icon" href="assets/images/logo.png" />
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">
    <style>
        .content-box { background: #ffffff; border-radius: 12px; border: 1px solid #e2e8f0; padding: 24px; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.05); }
    </style>
</head>
<body class="sidebar-icon-only">
  <div class="container-scroller">
    <!-- partial:partials/_navbar.html -->
    <nav class="navbar col-lg-12 col-12 p-0 fixed-top d-flex flex-row">
      <div class="text-center navbar-brand-wrapper d-flex align-items-center justify-content-start">
        <a class="navbar-brand brand-logo me-5" href="#" style="font-weight: 700; color: #4B49AC; font-size: 20px;"><i class="fas fa-radar me-2"></i>MonitorDaerah</a>
        <a class="navbar-brand brand-logo-mini" href="#"><i class="fas fa-radar"></i></a>
      </div>
      <div class="navbar-menu-wrapper d-flex align-items-center justify-content-end">
        <ul class="navbar-nav navbar-nav-right">
          <li class="nav-item nav-profile">
            <span class="text-dark me-4 mt-2 fw-bold"><i class="fas fa-user-shield me-1"></i> <?= htmlspecialchars($_SESSION['username']) ?></span>
            <a href="logout.php" class="btn btn-danger btn-sm px-3 py-2 fw-bold"><i class="fas fa-sign-out-alt me-1"></i> Logout</a>
          </li>
        </ul>
      </div>
    </nav>
    <!-- partial -->
    <div class="container-fluid page-body-wrapper">
      <div class="main-panel" style="width: 100%;">
        <div class="content-wrapper">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h3 class="fw-bold m-0 text-slate-800">Manajemen Instansi (SaaS)</h3>
            </div>

            <?= $msg ?>

            <div class="content-box border-primary" style="border-top: 4px solid #4B49AC;">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h5 class="fw-bold m-0"><i class="fas fa-building text-primary me-2"></i> Daftar Instansi Klien</h5>
                    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#modalInstansi" onclick="resetForm()"><i class="fas fa-plus me-1"></i> Tambah Instansi Baru</button>
                </div>
                
                <div class="table-responsive">
                    <table class="table table-hover align-middle" id="instansiTable">
                        <thead class="table-light">
                            <tr>
                                <th>ID</th>
                                <th>Nama Instansi</th>
                                <th>Akun Login (Admin & Pimpinan)</th>
                                <th>AI Agent & Model</th>
                                <th>API Key</th>
                                <th>Keyword Global</th>
                                <th>Status</th>
                                <th>Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach($instansi_list as $i): ?>
                            <tr>
                                <td><span class="badge bg-secondary">#<?= $i['id'] ?></span></td>
                                <td class="fw-bold"><?= htmlspecialchars($i['nama_instansi']) ?></td>
                                <td>
                                    <div class="mb-1"><span class="badge bg-info text-dark" title="Admin Instansi"><i class="fas fa-user-cog me-1"></i> <?= htmlspecialchars($i['username'] ?? 'Tidak ada') ?></span></div>
                                    <div><span class="badge bg-success" title="Executive Pimpinan"><i class="fas fa-user-tie me-1"></i> <?= htmlspecialchars($i['username_pimpinan'] ?? 'Tidak ada') ?></span></div>
                                </td>
                                <td>
                                    <div><small class="text-muted">Agent:</small> <span class="fw-bold"><?= htmlspecialchars($i['ai_agent'] ?? 'Groq') ?></span></div>
                                    <div><small class="text-muted">Model:</small> <span class="text-primary"><?= htmlspecialchars($i['ai_model'] ?? 'llama3-70b-8192') ?></span></div>
                                </td>
                                <td>
                                    <div class="text-truncate" style="max-width: 150px; font-family: monospace; font-size: 0.8rem;" title="<?= htmlspecialchars($i['api_key_ai']) ?>">
                                        <?= htmlspecialchars($i['api_key_ai']) ?>
                                    </div>
                                </td>
                                <td><small><?= htmlspecialchars($i['keyword_global']) ?></small></td>
                                <td>
                                    <?php if($i['status'] == 'aktif'): ?>
                                        <span class="badge bg-success">Aktif</span>
                                    <?php else: ?>
                                        <span class="badge bg-danger">Suspend</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <button class="btn btn-sm btn-light text-primary" title="Edit Instansi" onclick="editInstansi(<?= htmlspecialchars(json_encode($i)) ?>)">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    <form method="POST" class="d-inline" onsubmit="return confirm('Ubah status akses (login & cron) untuk instansi ini?');">
                                        <input type="hidden" name="action" value="toggle_status">
                                        <input type="hidden" name="id" value="<?= $i['id'] ?>">
                                        <input type="hidden" name="current_status" value="<?= $i['status'] ?>">
                                        <button type="submit" class="btn btn-sm btn-light <?= $i['status'] == 'aktif' ? 'text-warning' : 'text-success' ?>" title="<?= $i['status'] == 'aktif' ? 'Suspend Instansi' : 'Aktifkan Instansi' ?>">
                                            <i class="fas <?= $i['status'] == 'aktif' ? 'fa-power-off' : 'fa-play' ?>"></i>
                                        </button>
                                    </form>
                                    <form method="POST" class="d-inline" onsubmit="return confirm('Peringatan: Menghapus instansi akan menghapus akun adminnya juga. Yakin hapus?');">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="id" value="<?= $i['id'] ?>">
                                        <button type="submit" class="btn btn-sm btn-light text-danger" title="Hapus Instansi">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </form>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        <!-- content-wrapper ends -->
        <footer class="footer">
          <div class="d-sm-flex justify-content-center justify-content-sm-between">
            <span class="text-muted text-center text-sm-left d-block d-sm-inline-block">Copyright © 2026. MonitorDaerah All rights reserved.</span>
          </div>
        </footer>
      </div>
      <!-- main-panel ends -->
    </div>
    <!-- page-body-wrapper ends -->
  </div>

    <!-- Modal Form Instansi -->
    <div class="modal fade" id="modalInstansi" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content border-0 shadow">
                <div class="modal-header bg-primary text-white border-0">
                    <h5 class="modal-title" id="modalTitle">Tambah Instansi Klien</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST">
                    <div class="modal-body p-4 row">
                        <input type="hidden" name="action" id="formAction" value="add">
                        <input type="hidden" name="id" id="formId" value="">
                        
                        <div class="col-md-12 mb-3">
                            <label class="form-label fw-bold">Nama Instansi</label>
                            <input type="text" name="nama_instansi" id="formNama" class="form-control" required placeholder="Contoh: Pemko Banjarbaru">
                        </div>

                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-bold">Username Admin Instansi</label>
                            <input type="text" name="username" id="formUsername" class="form-control bg-light" required placeholder="Username admin">
                            <small class="text-muted" id="userHelp">Admin memakai ini untuk login.</small>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-bold">Password Admin Instansi</label>
                            <input type="password" name="password" id="formPassword" class="form-control" required placeholder="Minimal 6 karakter">
                            <small class="text-muted" id="pwHelp">Kosongkan saat edit jika tidak ganti.</small>
                        </div>

                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-bold">Username Pimpinan</label>
                            <input type="text" name="username_pimpinan" id="formUsernamePimpinan" class="form-control bg-light" placeholder="Opsional (Dashboard Only)">
                            <small class="text-muted" id="userPimpinanHelp">Akses read-only khusus pimpinan.</small>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-bold">Password Pimpinan</label>
                            <input type="password" name="password_pimpinan" id="formPasswordPimpinan" class="form-control" placeholder="Minimal 6 karakter">
                            <small class="text-muted" id="pwPimpinanHelp">Kosongkan saat edit jika tidak ganti.</small>
                        </div>
                        
                        <div class="col-md-12 mb-3">
                            <label class="form-label fw-bold">Email Google Login (Opsional)</label>
                            <input type="text" name="email" id="formEmail" class="form-control" placeholder="admin@gmail.com, admin2@gmail.com">
                            <small class="text-muted">Pisahkan dengan koma jika ada lebih dari 1 email yang bisa masuk ke akun ini via Google Login.</small>
                        </div>

                        <div class="col-md-12 mb-3">
                            <hr>
                            <h6 class="fw-bold text-primary"><i class="fas fa-brain me-2"></i> Konfigurasi AI Engine</h6>
                        </div>

                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-bold">AI Agent Provider</label>
                            <select name="ai_agent" id="formAgent" class="form-select">
                                <option value="Groq">Groq (Cepat & Gratis)</option>
                                <option value="OpenAI">OpenAI (ChatGPT)</option>
                                <option value="Claude">Anthropic Claude</option>
                                <option value="Gemini">Google Gemini</option>
                                <option value="KoboiLLM">KoboiLLM</option>
                            </select>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-bold">AI Model</label>
                            <input type="text" name="ai_model" id="formModel" class="form-control" value="llama3-70b-8192" required placeholder="Contoh: llama3-70b-8192">
                        </div>

                        <div class="col-md-12 mb-3">
                            <label class="form-label fw-bold">API Key</label>
                            <input type="text" name="api_key_ai" id="formApiKey" class="form-control" required placeholder="Masukkan API Key yang valid">
                        </div>

                        <div class="col-md-12 mb-3">
                            <label class="form-label fw-bold">Keyword Global Scraping (Opsional tapi penting)</label>
                            <textarea name="keyword_global" id="formKeyword" class="form-control" rows="2" placeholder="Contoh: Pemko Banjarbaru, Aditya Mufti, Banjarbaru Juara"></textarea>
                            <small class="text-muted">Pisahkan dengan koma. Jika diisi, engine hanya akan mengambil berita yang mengandung minimal 1 keyword ini.</small>
                        </div>
                    </div>
                    <div class="modal-footer bg-light border-0">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                        <button type="submit" class="btn btn-primary fw-bold"><i class="fas fa-save me-1"></i> Simpan Data</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- plugins:js -->
    <script src="assets_skydash/vendors/js/vendor.bundle.base.js"></script>
    <!-- endinject -->
    <script src="https://code.jquery.com/jquery-3.7.0.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
    <!-- inject:js -->
    <script src="assets_skydash/js/off-canvas.js"></script>
    <script src="assets_skydash/js/template.js"></script>
    <script src="assets_skydash/js/settings.js"></script>
    <!-- endinject -->

    <script>
        $(document).ready(function() {
            $('#instansiTable').DataTable({
                "pageLength": 25,
                "language": {
                    "search": "Pencarian:",
                    "lengthMenu": "Tampilkan _MENU_ data",
                    "info": "Menampilkan _START_ s/d _END_ dari _TOTAL_ instansi",
                    "infoEmpty": "Data kosong",
                    "zeroRecords": "Tidak ada data yang ditemukan",
                    "paginate": { "first": "Awal", "last": "Akhir", "next": ">>", "previous": "<<" }
                }
            });
        });

        function resetForm() {
            document.getElementById('formAction').value = 'add';
            document.getElementById('formId').value = '';
            document.getElementById('formNama').value = '';
            document.getElementById('formUsername').value = '';
            document.getElementById('formPassword').value = '';
            document.getElementById('formPassword').required = true;
            document.getElementById('formUsernamePimpinan').value = '';
            document.getElementById('formPasswordPimpinan').value = '';
            document.getElementById('formEmail').value = '';
            document.getElementById('formAgent').value = 'Groq';
            document.getElementById('formModel').value = 'llama3-70b-8192';
            document.getElementById('formApiKey').value = '';
            document.getElementById('formKeyword').value = '';
            
            document.getElementById('modalTitle').innerText = 'Tambah Instansi Baru';
            document.getElementById('formUsername').readOnly = false;
            document.getElementById('formUsernamePimpinan').readOnly = false;
            document.getElementById('userHelp').innerText = 'Admin instansi akan memakai ini untuk login.';
            document.getElementById('pwHelp').innerText = 'Minimal 6 karakter.';
        }

        function editInstansi(data) {
            document.getElementById('formAction').value = 'edit';
            document.getElementById('formId').value = data.id;
            document.getElementById('formNama').value = data.nama_instansi;
            document.getElementById('formUsername').value = data.username ? data.username : '';
            document.getElementById('formPassword').value = '';
            document.getElementById('formPassword').required = false; // tidak wajib isi kalau edit
            document.getElementById('formUsernamePimpinan').value = data.username_pimpinan ? data.username_pimpinan : '';
            document.getElementById('formPasswordPimpinan').value = '';
            document.getElementById('formEmail').value = data.email ? data.email : '';
            document.getElementById('formAgent').value = data.ai_agent;
            document.getElementById('formModel').value = data.ai_model;
            document.getElementById('formApiKey').value = data.api_key_ai;
            document.getElementById('formKeyword').value = data.keyword_global;

            document.getElementById('modalTitle').innerText = 'Edit Instansi';
            document.getElementById('formUsername').readOnly = true;
            document.getElementById('formUsernamePimpinan').readOnly = false;
            document.getElementById('userHelp').innerHTML = '<span class="text-danger">Username tidak dapat diubah.</span>';
            document.getElementById('pwHelp').innerText = 'Kosongkan jika tidak ingin reset password.';

            var myModal = new bootstrap.Modal(document.getElementById('modalInstansi'));
            myModal.show();
        }
    </script>
</body>
</html>