<?php
/**
 * admin/kelola_live.php - Manajemen Karakter Gemini Live
 * Fitur: Ganti Foto, Nama, Deskripsi & Setting Suara
 * 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; 
}

// 1. MIGRASI: Buat tabel jika belum ada
$sql_migration = "CREATE TABLE IF NOT EXISTS live_characters (
    id INT AUTO_INCREMENT PRIMARY KEY,
    char_key VARCHAR(50) UNIQUE NOT NULL,
    name VARCHAR(100) NOT NULL,
    description TEXT,
    image_path VARCHAR(255) NOT NULL,
    pitch FLOAT DEFAULT 1.0,
    rate FLOAT DEFAULT 1.1,
    status_text VARCHAR(255)
)";
mysqli_query($conn, $sql_migration);

// 2. SEEDING: Isi data default jika masih kosong
$check_empty = mysqli_query($conn, "SELECT COUNT(*) as total FROM live_characters");
$row_empty = mysqli_fetch_assoc($check_empty);
if ($row_empty['total'] == 0) {
    $seed_sql = "INSERT INTO live_characters (char_key, name, description, image_path, pitch, rate, status_text) VALUES
    ('abg', 'ABG (Ceria)', 'Suara imut & enerjik', 'uploads/avatar_abg.png', 1.3, 1.2, 'Bicara sama ABG Ceria...'),
    ('remaja', 'Remaja (Stylish)', 'Suara santai & asik', 'uploads/avatar_remaja.png', 1.0, 1.1, 'Bicara sama Remaja Stylish...'),
    ('dewasa', 'Dewasa (Bijak)', 'Suara tenang & formal', 'uploads/avatar_dewasa.png', 0.85, 0.95, 'Bicara sama AI Dewasa Bijak...')";
    mysqli_query($conn, $seed_sql);
}

$msg = "";

// 3. PROSES SIMPAN PERUBAHAN
if (isset($_POST['save_char'])) {
    $id = (int)$_POST['char_id'];
    $name = mysqli_real_escape_string($conn, $_POST['name']);
    $desc = mysqli_real_escape_string($conn, $_POST['description']);
    $pitch = (float)$_POST['pitch'];
    $rate = (float)$_POST['rate'];
    $status = mysqli_real_escape_string($conn, $_POST['status_text']);
    $style = mysqli_real_escape_string($conn, $_POST['speech_style']);

    // Handle Upload Foto Baru
    $image_update = "";
    if (isset($_FILES['char_photo']) && $_FILES['char_photo']['error'] == 0) {
        $allowed = ['jpg', 'jpeg', 'png', 'webp'];
        $filename = $_FILES['char_photo']['name'];
        $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
        
        if (in_array($ext, $allowed)) {
            $new_filename = 'avatar_' . $_POST['char_key'] . '_' . time() . '.' . $ext;
            $upload_dir = '../uploads/';
            if (!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);
            
            if (move_uploaded_file($_FILES['char_photo']['tmp_name'], $upload_dir . $new_filename)) {
                $image_path = 'uploads/' . $new_filename;
                $image_update = ", image_path = '$image_path'";
            }
        } else {
            $msg = "<div class='alert alert-danger'>Format foto tidak didukung!</div>";
        }
    }

    if (empty($msg)) {
        $sql = "UPDATE live_characters SET 
                name = '$name', description = '$desc',
                pitch = '$pitch', rate = '$rate',
                status_text = '$status',
                speech_style = '$style'
                $image_update
                WHERE id = $id";
        
        if (mysqli_query($conn, $sql)) {
            $msg = "<div class='alert alert-success border-0 shadow-sm rounded-3 mb-4'><strong>Berhasil!</strong> Karakter telah diperbarui.</div>";
        } else {
            $msg = "<div class='alert alert-danger'>Error: " . mysqli_error($conn) . "</div>";
        }
    }
}

// Ambil semua karakter
$query = mysqli_query($conn, "SELECT * FROM live_characters ORDER BY id ASC");
$characters = [];
while ($row = mysqli_fetch_assoc($query)) {
    $characters[] = $row;
}

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

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Kelola Karakter Live | <?= 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;
        }
        body { background-color: var(--bg-color); font-family: 'Plus Jakarta Sans', sans-serif; color: var(--text-dark); }
        .glass-card {
            background: rgba(255, 255, 255, 0.95);
            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-hero { 
            background: linear-gradient(135deg, #2563eb 0%, #1e40af 100%); 
            padding: 35px; 
            text-align: center; 
            color: white; 
        }
        .char-card {
            background: #fff;
            border-radius: 16px;
            border: 1px solid #e2e8f0;
            padding: 20px;
            margin-bottom: 20px;
            transition: 0.3s;
        }
        .char-card:hover { transform: translateY(-5px); box-shadow: 0 10px 20px rgba(0,0,0,0.05); }
        .avatar-preview {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            object-fit: cover;
            border: 3px solid #e2e8f0;
        }
        .form-label { font-size: 0.75rem; text-transform: uppercase; font-weight: 700; color: #64748b; letter-spacing: 0.5px; }
    </style>
</head>
<body class="py-5">

<div class="container">
    <div class="row justify-content-center">
        <div class="col-lg-10">
            
            <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>
                <h5 class="fw-bold m-0 text-dark">Manajemen Live</h5>
            </div>

            <div class="glass-card">
                <div class="header-hero">
                    <i class="bi bi-person-bounding-box fs-1 mb-2 d-block opacity-75"></i>
                    <h3 class="fw-bold mb-1">Kelola Karakter Live</h3>
                    <p class="opacity-75 mb-0 font-monospace small">CUSTOMIZE YOUR AI AVATARS</p>
                </div>

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

                    <div class="row">
                        <?php foreach ($characters as $char): ?>
                        <div class="col-12">
                            <form method="POST" enctype="multipart/form-data" class="char-card">
                                <input type="hidden" name="char_id" value="<?= $char['id'] ?>">
                                <input type="hidden" name="char_key" value="<?= $char['char_key'] ?>">
                                
                                <div class="row align-items-center g-4">
                                    <div class="col-md-2 text-center">
                                        <img src="../<?= htmlspecialchars($char['image_path']) ?>" class="avatar-preview mb-3">
                                        <div class="position-relative">
                                            <input type="file" name="char_photo" class="form-control form-control-sm" accept="image/*" style="font-size: 10px;">
                                            <small class="text-muted d-block mt-1" style="font-size: 10px;">Ganti Foto</small>
                                        </div>
                                    </div>
                                    
                                    <div class="col-md-10">
                                        <div class="row g-3">
                                            <div class="col-md-4">
                                                <label class="form-label">Nama Karakter</label>
                                                <input type="text" name="name" class="form-control fw-bold" value="<?= htmlspecialchars($char['name']) ?>" required>
                                            </div>
                                            <div class="col-md-4">
                                                <label class="form-label">Gaya Bicara</label>
                                                <select name="speech_style" class="form-select fw-bold">
                                                    <option value="manja" <?= $char['speech_style'] == 'manja' ? 'selected' : '' ?>>Manja & Gemas</option>
                                                    <option value="ramah" <?= $char['speech_style'] == 'ramah' ? 'selected' : '' ?>>Ramah & Sopan</option>
                                                    <option value="humoris" <?= $char['speech_style'] == 'humoris' ? 'selected' : '' ?>>Humoris & Santai</option>
                                                    <option value="formal" <?= $char['speech_style'] == 'formal' ? 'selected' : '' ?>>Formal & Bijak</option>
                                                </select>
                                            </div>
                                            <div class="col-md-8">
                                                <label class="form-label">Status Text (Saat Aktif)</label>
                                                <input type="text" name="status_text" class="form-control" value="<?= htmlspecialchars($char['status_text']) ?>" required>
                                            </div>
                                            <div class="col-md-12">
                                                <label class="form-label">Deskripsi Singkat</label>
                                                <input type="text" name="description" class="form-control text-muted" value="<?= htmlspecialchars($char['description']) ?>">
                                            </div>
                                            <div class="col-md-3">
                                                <label class="form-label">Voice Pitch (0.5 - 2.0)</label>
                                                <input type="number" step="0.05" name="pitch" class="form-control" value="<?= $char['pitch'] ?>" required>
                                            </div>
                                            <div class="col-md-3">
                                                <label class="form-label">Voice Rate (0.5 - 2.0)</label>
                                                <input type="number" step="0.05" name="rate" class="form-control" value="<?= $char['rate'] ?>" required>
                                            </div>
                                            <div class="col-md-6 d-flex align-items-end">
                                                <button type="submit" name="save_char" class="btn btn-primary w-100 fw-bold rounded-3">
                                                    <i class="bi bi-save me-2"></i> Simpan Karakter <?= htmlspecialchars($char['char_key']) ?>
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </form>
                        </div>
                        <?php endforeach; ?>
                    </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>
