<?php
require_once $_SERVER['DOCUMENT_ROOT'] . '/yoga/includes/config.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/yoga/includes/functions.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/yoga/includes/header.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/yoga/includes/sidebar.php';

// Cek login & akses admin
cek_login();
if ($_SESSION['role'] != 'admin') {
    header("Location: " . BASE_URL . "/index.php?access=denied");
    exit();
}

// Ambil pengaturan
$query = "SELECT * FROM pengaturan WHERE id = 1";
$result = mysqli_query($conn, $query);
$data = mysqli_fetch_assoc($result);

$error = '';
$success = '';

// Proses edit
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $nama_perusahaan = sanitize($_POST['nama_perusahaan']);
    $alamat = sanitize($_POST['alamat']);
    $telepon = sanitize($_POST['telepon']);
    $email = sanitize($_POST['email']);
    $jam_masuk = sanitize($_POST['jam_masuk']);
    $jam_keluar = sanitize($_POST['jam_keluar']);
    $toleransi_keterlambatan = (int)sanitize($_POST['toleransi_keterlambatan']);
    $potongan_keterlambatan = (int)sanitize($_POST['potongan_keterlambatan']);
    $potongan_alpha = (int)sanitize($_POST['potongan_alpha']);
    
    if (empty($nama_perusahaan) || empty($jam_masuk) || empty($jam_keluar)) {
        $error = "Nama perusahaan, jam masuk, dan jam keluar harus diisi!";
    } else {
        $logo_name = $data['logo']; // Keep old logo by default
        
        // Upload logo jika ada
        if (isset($_FILES['logo']) && $_FILES['logo']['error'] == 0) {
            $allowed_types = ['image/jpeg', 'image/jpg', 'image/png'];
            $file_type = $_FILES['logo']['type'];
            $file_size = $_FILES['logo']['size'];
            
            if (!in_array($file_type, $allowed_types)) {
                $error = "Tipe file logo tidak didukung (hanya JPG, JPEG, PNG).";
            } elseif ($file_size > 2097152) { // 2MB
                $error = "Ukuran file logo terlalu besar. Maksimal 2MB.";
            } else {
                $file_extension = pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION);
                $new_logo_name = 'logo_' . time() . '.' . $file_extension;
                $upload_dir = $_SERVER['DOCUMENT_ROOT'] . '/yoga/assets/img/';
                
                if (!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);
                
                if (move_uploaded_file($_FILES['logo']['tmp_name'], $upload_dir . $new_logo_name)) {
                    // Hapus logo lama jika bukan default
                    if (!empty($data['logo']) && $data['logo'] != 'logo.png' && file_exists($upload_dir . $data['logo'])) {
                        unlink($upload_dir . $data['logo']);
                    }
                    $logo_name = $new_logo_name;
                } else {
                    $error = "Gagal mengupload logo!";
                }
            }
        }
        
        if (empty($error)) {
            $update_query = "UPDATE pengaturan SET 
                            nama_perusahaan = '$nama_perusahaan',
                            alamat = '$alamat',
                            telepon = '$telepon',
                            email = '$email',
                            logo = '$logo_name',
                            jam_masuk = '$jam_masuk',
                            jam_keluar = '$jam_keluar',
                            toleransi_keterlambatan = $toleransi_keterlambatan,
                            potongan_keterlambatan = $potongan_keterlambatan,
                            potongan_alpha = $potongan_alpha,
                            updated_at = NOW()
                            WHERE id = 1";
            
            if (mysqli_query($conn, $update_query)) {
                header("Location: " . $_SERVER['PHP_SELF'] . "?success=" . urlencode("Pengaturan berhasil diperbarui!"));
                exit();
            } else {
                $error = "Gagal memperbarui pengaturan: " . mysqli_error($conn);
            }
        }
    }
}
if(isset($_GET['success'])) $success = htmlspecialchars($_GET['success']);
if(isset($_GET['error'])) $error = htmlspecialchars($_GET['error']);
?>

<!-- Main Content -->
<div class="main-content flex-1 p-8">
    <div class="mb-6">
        <h2 class="text-3xl font-bold text-white">Pengaturan Aplikasi</h2>
        <p class="text-slate-400">Kelola informasi umum, absensi, dan penggajian perusahaan.</p>
    </div>
    
    <?php if (!empty($success)): ?>
    <div class="bg-green-500/20 border border-green-500/30 text-green-300 px-4 py-3 rounded-lg relative mb-6 text-sm flex items-center gap-3" role="alert"><i class="fas fa-check-circle"></i><span><?php echo $success; ?></span></div>
    <?php endif; ?>
    <?php if (!empty($error)): ?>
    <div class="bg-red-500/20 border border-red-500/30 text-red-300 px-4 py-3 rounded-lg relative mb-6 text-sm flex items-center gap-3" role="alert"><i class="fas fa-exclamation-circle"></i><span><?php echo $error; ?></span></div>
    <?php endif; ?>
    
    <div class="glass-effect p-6 rounded-xl shadow-lg">
        <form method="POST" action="" enctype="multipart/form-data">
            <!-- Tabs Navigation -->
            <div class="mb-6">
                <div class="border-b border-slate-700/50">
                     <nav class="-mb-px flex space-x-6" aria-label="Tabs">
                         <button type="button" onclick="changeTab(this, 'tab-perusahaan')" class="tab-button active">Informasi Perusahaan</button>
                         <button type="button" onclick="changeTab(this, 'tab-absensi')" class="tab-button">Absensi & Gaji</button>
                     </nav>
                </div>
            </div>

            <!-- Tab Content: Perusahaan -->
            <div id="tab-perusahaan" class="tab-content">
                <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
                    <div class="space-y-4">
                        <div>
                            <label for="nama_perusahaan" class="block text-slate-400 text-sm font-medium mb-2">Nama Perusahaan <span class="text-red-400">*</span></label>
                            <input type="text" name="nama_perusahaan" id="nama_perusahaan" value="<?php echo htmlspecialchars($data['nama_perusahaan']); ?>" class="w-full border border-slate-600 bg-slate-700/50 text-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-sky-500 px-3 py-2.5" required>
                        </div>
                        <div>
                            <label for="alamat" class="block text-slate-400 text-sm font-medium mb-2">Alamat</label>
                            <textarea name="alamat" id="alamat" rows="3" class="w-full border border-slate-600 bg-slate-700/50 text-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-sky-500 px-3 py-2.5"><?php echo htmlspecialchars($data['alamat']); ?></textarea>
                        </div>
                    </div>
                    <div class="space-y-4">
                        <div>
                            <label for="telepon" class="block text-slate-400 text-sm font-medium mb-2">Telepon</label>
                            <input type="text" name="telepon" id="telepon" value="<?php echo htmlspecialchars($data['telepon']); ?>" class="w-full border border-slate-600 bg-slate-700/50 text-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-sky-500 px-3 py-2.5">
                        </div>
                        <div>
                            <label for="email" class="block text-slate-400 text-sm font-medium mb-2">Email</label>
                            <input type="email" name="email" id="email" value="<?php echo htmlspecialchars($data['email']); ?>" class="w-full border border-slate-600 bg-slate-700/50 text-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-sky-500 px-3 py-2.5">
                        </div>
                        <div>
                            <label for="logo" class="block text-slate-400 text-sm font-medium mb-2">Logo Perusahaan</label>
                             <input type="file" name="logo" id="logo" class="w-full text-sm text-slate-400 file:mr-4 file:py-2 file:px-4 file:rounded-lg file:border-0 file:text-sm file:font-semibold file:bg-sky-600/50 file:text-sky-300 hover:file:bg-sky-600/70" accept="image/jpeg,image/jpg,image/png">
                            <p class="text-slate-500 text-xs mt-1">Format: JPG, PNG. Maks: 2MB. Kosongkan jika tidak ingin mengubah.</p>
                            <?php if (!empty($data['logo']) && file_exists($_SERVER['DOCUMENT_ROOT'] . '/yoga/assets/img/' . $data['logo'])): ?>
                            <img src="<?php echo BASE_URL; ?>/assets/img/<?php echo htmlspecialchars($data['logo']); ?>" alt="Logo Saat Ini" class="h-16 mt-3 bg-white/10 p-2 rounded-lg">
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Tab Content: Absensi & Gaji (RESTRUCTURED) -->
            <div id="tab-absensi" class="tab-content hidden">
                 <div class="grid grid-cols-1 lg:grid-cols-2 gap-x-8 gap-y-6">
                    <!-- Kolom 1 -->
                    <div class="space-y-4">
                         <div>
                            <label for="jam_masuk" class="block text-slate-400 text-sm font-medium mb-2">Jam Masuk <span class="text-red-400">*</span></label>
                            <input type="time" name="jam_masuk" id="jam_masuk" value="<?php echo htmlspecialchars($data['jam_masuk']); ?>" class="w-full border border-slate-600 bg-slate-700/50 text-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-sky-500 px-3 py-2.5" required>
                        </div>
                        <div>
                            <label for="jam_keluar" class="block text-slate-400 text-sm font-medium mb-2">Jam Keluar <span class="text-red-400">*</span></label>
                            <input type="time" name="jam_keluar" id="jam_keluar" value="<?php echo htmlspecialchars($data['jam_keluar']); ?>" class="w-full border border-slate-600 bg-slate-700/50 text-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-sky-500 px-3 py-2.5" required>
                        </div>
                         <div>
                            <label for="toleransi_keterlambatan" class="block text-slate-400 text-sm font-medium mb-2">Toleransi Keterlambatan (menit)</label>
                            <input type="number" name="toleransi_keterlambatan" id="toleransi_keterlambatan" value="<?php echo htmlspecialchars($data['toleransi_keterlambatan']); ?>" class="w-full border border-slate-600 bg-slate-700/50 text-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-sky-500 px-3 py-2.5">
                        </div>
                    </div>

                    <!-- Kolom 2 -->
                     <div class="space-y-4">
                        <div>
                            <label for="potongan_keterlambatan" class="block text-slate-400 text-sm font-medium mb-2">Potongan per Jam Terlambat (Rp)</label>
                            <input type="number" name="potongan_keterlambatan" id="potongan_keterlambatan" value="<?php echo htmlspecialchars($data['potongan_keterlambatan']); ?>" class="w-full border border-slate-600 bg-slate-700/50 text-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-sky-500 px-3 py-2.5">
                        </div>
                        <div>
                            <label for="potongan_alpha" class="block text-slate-400 text-sm font-medium mb-2">Potongan Alpha / Tidak Hadir (Rp)</label>
                            <input type="number" name="potongan_alpha" id="potongan_alpha" value="<?php echo htmlspecialchars($data['potongan_alpha']); ?>" class="w-full border border-slate-600 bg-slate-700/50 text-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-sky-500 px-3 py-2.5">
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="mt-8 border-t border-slate-700/50 pt-6 flex justify-end">
                <button type="submit" class="bg-sky-600 hover:bg-sky-700 text-white font-bold py-2.5 px-6 rounded-lg transition-colors flex items-center gap-2">
                    <i class="fas fa-save"></i> Simpan Pengaturan
                </button>
            </div>
        </form>
    </div>
</div>

<style>
    .tab-button { @apply border-transparent text-slate-400 hover:text-white hover:border-slate-400 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm transition-all; }
    .tab-button.active { @apply border-sky-500 text-sky-400; }
    
    /* Removed custom .form-label and .form-input classes */

    .file-input { @apply w-full text-sm text-slate-400 file:mr-4 file:py-2 file:px-4 file:rounded-lg file:border-0 file:text-sm file:font-semibold file:bg-sky-600/50 file:text-sky-300 hover:file:bg-sky-600/70; }

    /* Final fix for browser autofill */
    input:-webkit-autofill,
    input:-webkit-autofill:hover, 
    input:-webkit-autofill:focus,
    input:-webkit-autofill:active {
        -webkit-background-clip: text;
        -webkit-text-fill-color: #e2e8f0 !important; /* slate-200 */
        transition: background-color 5000s ease-in-out 0s;
        box-shadow: inset 0 0 20px 20px #1e293b; /* slate-800 */
        caret-color: #e2e8f0;
    }
    
    input[type="time"]::-webkit-calendar-picker-indicator {
        filter: invert(1);
    }
</style>

<script>
    function changeTab(button, tabId) {
        document.querySelectorAll('.tab-content').forEach(tab => tab.classList.add('hidden'));
        document.querySelectorAll('.tab-button').forEach(btn => btn.classList.remove('active'));
        document.getElementById(tabId).classList.remove('hidden');
        button.classList.add('active');
    }
</script>

<?php
require_once $_SERVER['DOCUMENT_ROOT'] . '/yoga/includes/footer.php';
?>
