<?php
require_once '../config/connection.php';
checkUserType(['superadmin']);

$type = $_GET['type'] ?? 'asset';
$message = '';
$message_type = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    try {
        if ($type == 'asset') {
            // Add Asset
            $asset_number = sanitize($_POST['asset_number']);
            $asset_name = sanitize($_POST['asset_name']);
            $asset_category = sanitize($_POST['asset_category']);
            $barcode_number = sanitize($_POST['barcode_number']);
            $kode_material_sap = sanitize($_POST['kode_material_sap']);
            $description = sanitize($_POST['description']);
            
            // Check if asset number already exists
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM assets WHERE asset_number = ?");
            $stmt->execute([$asset_number]);
            
            if ($stmt->fetchColumn() > 0) {
                $message = 'Asset number sudah ada! Gunakan nomor yang berbeda.';
                $message_type = 'error';
            } else {
                $stmt = $pdo->prepare("
                    INSERT INTO assets (asset_number, asset_name, asset_category, barcode_number, kode_material_sap, description) 
                    VALUES (?, ?, ?, ?, ?, ?)
                ");
                $stmt->execute([$asset_number, $asset_name, $asset_category, $barcode_number, $kode_material_sap, $description]);
                
                $message = 'Asset berhasil ditambahkan!';
                $message_type = 'success';
            }
            
        } elseif ($type == 'admin') {
            // Add Admin
            $nik = sanitize($_POST['nik']);
            $employee_id = sanitize($_POST['employee_id']);
            $password = hash('sha256', $_POST['password']);
            $full_name = sanitize($_POST['full_name']);
            $branch_name = sanitize($_POST['branch_name']);
            $organization = sanitize($_POST['organization']);
            $jabatan = sanitize($_POST['jabatan']);
            
            // Check if NIK or employee_id already exists
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM admins WHERE nik = ? OR employee_id = ?");
            $stmt->execute([$nik, $employee_id]);
            
            if ($stmt->fetchColumn() > 0) {
                $message = 'NIK atau Employee ID sudah ada!';
                $message_type = 'error';
            } else {
                $stmt = $pdo->prepare("
                    INSERT INTO admins (nik, employee_id, password, full_name, branch_name, organization, jabatan) 
                    VALUES (?, ?, ?, ?, ?, ?, ?)
                ");
                $stmt->execute([$nik, $employee_id, $password, $full_name, $branch_name, $organization, $jabatan]);
                
                $message = 'Admin berhasil ditambahkan!';
                $message_type = 'success';
            }
            
        } elseif ($type == 'borrower') {
            // Add Borrower
            $nik = sanitize($_POST['nik']);
            $employee_id = sanitize($_POST['employee_id']);
            $password = hash('sha256', $_POST['password']);
            $full_name = sanitize($_POST['full_name']);
            $branch_name = sanitize($_POST['branch_name']);
            $organization = sanitize($_POST['organization']);
            $jabatan = sanitize($_POST['jabatan']);
            
            // Check if NIK or employee_id already exists
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM borrowers WHERE nik = ? OR employee_id = ?");
            $stmt->execute([$nik, $employee_id]);
            
            if ($stmt->fetchColumn() > 0) {
                $message = 'NIK atau Employee ID sudah ada!';
                $message_type = 'error';
            } else {
                $stmt = $pdo->prepare("
                    INSERT INTO borrowers (nik, employee_id, password, full_name, branch_name, organization, jabatan) 
                    VALUES (?, ?, ?, ?, ?, ?, ?)
                ");
                $stmt->execute([$nik, $employee_id, $password, $full_name, $branch_name, $organization, $jabatan]);
                
                $message = 'Borrower berhasil ditambahkan!';
                $message_type = 'success';
            }
        }
    } catch (Exception $e) {
        $message = 'Terjadi kesalahan: ' . $e->getMessage();
        $message_type = 'error';
    }
}

// Page titles and back links
$page_info = [
    'asset' => ['title' => 'Tambah Asset', 'back' => 'assets.php'],
    'admin' => ['title' => 'Tambah Admin', 'back' => 'users.php'],
    'borrower' => ['title' => 'Tambah Borrower', 'back' => 'users.php']
];
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $page_info[$type]['title']; ?> - Peminjaman Tools Room</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        'leaf-green': '#90EE90',
                        'dark-leaf': '#32CD32',
                        'soft-gray': '#F5F5F5',
                        'medium-gray': '#9CA3AF'
                    }
                }
            }
        }
    </script>
</head>
<body class="bg-soft-gray min-h-screen">
    <!-- Header -->
    <header class="bg-white shadow-sm border-b-2 border-leaf-green">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between items-center py-4">
                <div class="flex items-center space-x-4">
                    <a href="<?php echo $page_info[$type]['back']; ?>" class="text-dark-leaf hover:text-green-600">
                        <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"></path>
                        </svg>
                    </a>
                    <img src="../images/logo.png" alt="Logo" class="h-10 w-10" onerror="this.style.display='none'">
                    <div>
                        <h1 class="text-xl font-bold text-gray-800"><?php echo $page_info[$type]['title']; ?></h1>
                        <p class="text-sm text-medium-gray">Tambah data baru ke sistem</p>
                    </div>
                </div>
                <div class="flex items-center space-x-4">
                    <span class="text-sm text-gray-600"><?php echo $_SESSION['user_name']; ?></span>
                    <a href="../logout.php" class="bg-red-500 hover:bg-red-600 text-white px-4 py-2 rounded-lg text-sm transition duration-200">
                        Logout
                    </a>
                </div>
            </div>
        </div>
    </header>

    <div class="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <!-- Type Selector -->
        <div class="bg-white rounded-xl shadow-lg p-6 mb-8">
            <h2 class="text-lg font-semibold text-gray-800 mb-4">Pilih Jenis Data</h2>
            <div class="flex flex-wrap gap-2">
                <a href="?type=asset" class="px-4 py-2 rounded-lg text-sm font-medium transition duration-200 <?php echo $type == 'asset' ? 'bg-dark-leaf text-white' : 'bg-soft-gray text-gray-600 hover:bg-leaf-green hover:text-white'; ?>">
                    Asset
                </a>
                <a href="?type=admin" class="px-4 py-2 rounded-lg text-sm font-medium transition duration-200 <?php echo $type == 'admin' ? 'bg-dark-leaf text-white' : 'bg-soft-gray text-gray-600 hover:bg-leaf-green hover:text-white'; ?>">
                    Admin
                </a>
                <a href="?type=borrower" class="px-4 py-2 rounded-lg text-sm font-medium transition duration-200 <?php echo $type == 'borrower' ? 'bg-dark-leaf text-white' : 'bg-soft-gray text-gray-600 hover:bg-leaf-green hover:text-white'; ?>">
                    Borrower
                </a>
            </div>
        </div>

        <!-- Message -->
        <?php if ($message): ?>
        <div class="mb-6 p-4 rounded-lg <?php echo $message_type == 'success' ? 'bg-green-100 border border-green-400 text-green-700' : 'bg-red-100 border border-red-400 text-red-700'; ?>">
            <?php echo $message; ?>
        </div>
        <?php endif; ?>

        <!-- Form -->
        <div class="bg-white rounded-xl shadow-lg p-6">
            <?php if ($type == 'asset'): ?>
            <!-- Asset Form -->
            <form method="POST" class="space-y-6">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <label for="asset_number" class="block text-sm font-medium text-gray-700 mb-2">
                            Asset Number <span class="text-red-500">*</span>
                        </label>
                        <input type="text" id="asset_number" name="asset_number" required
                               class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-dark-leaf focus:border-dark-leaf"
                               placeholder="Contoh: AST004">
                    </div>
                    <div>
                        <label for="asset_name" class="block text-sm font-medium text-gray-700 mb-2">
                            Nama Asset <span class="text-red-500">*</span>
                        </label>
                        <input type="text" id="asset_name" name="asset_name" required
                               class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-dark-leaf focus:border-dark-leaf"
                               placeholder="Nama asset">
                    </div>
                    <div>
                        <label for="asset_category" class="block text-sm font-medium text-gray-700 mb-2">
                            Kategori <span class="text-red-500">*</span>
                        </label>
                        <select id="asset_category" name="asset_category" required
                                class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-dark-leaf focus:border-dark-leaf">
                            <option value="">Pilih Kategori</option>
                            <option value="Electronics">Electronics</option>
                            <option value="Tools">Tools</option>
                            <option value="Furniture">Furniture</option>
                            <option value="Vehicle">Vehicle</option>
                            <option value="Others">Others</option>
                        </select>
                    </div>
                    <div>
                        <label for="barcode_number" class="block text-sm font-medium text-gray-700 mb-2">
                            Barcode Number
                        </label>
                        <input type="text" id="barcode_number" name="barcode_number"
                               class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-dark-leaf focus:border-dark-leaf"
                               placeholder="Barcode number">
                    </div>
                    <div>
                        <label for="kode_material_sap" class="block text-sm font-medium text-gray-700 mb-2">
                            Kode Material SAP
                        </label>
                        <input type="text" id="kode_material_sap" name="kode_material_sap"
                               class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-dark-leaf focus:border-dark-leaf"
                               placeholder="SAP material code">
                    </div>
                </div>
                <div>
                    <label for="description" class="block text-sm font-medium text-gray-700 mb-2">
                        Deskripsi
                    </label>
                    <textarea id="description" name="description" rows="3"
                              class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-dark-leaf focus:border-dark-leaf"
                              placeholder="Deskripsi asset..."></textarea>
                </div>
                <div class="flex space-x-4">
                    <button type="submit" class="bg-dark-leaf hover:bg-green-600 text-white px-6 py-3 rounded-lg transition duration-200 font-semibold">
                        Tambah Asset
                    </button>
                    <a href="assets.php" class="bg-medium-gray hover:bg-gray-600 text-white px-6 py-3 rounded-lg transition duration-200 font-semibold">
                        Batal
                    </a>
                </div>
            </form>

            <?php elseif ($type == 'admin' || $type == 'borrower'): ?>
            <!-- User Form -->
            <form method="POST" class="space-y-6">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <label for="nik" class="block text-sm font-medium text-gray-700 mb-2">
                            NIK Perusahaan <span class="text-red-500">*</span>
                        </label>
                        <input type="text" id="nik" name="nik" required
                               class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-dark-leaf focus:border-dark-leaf"
                               placeholder="NIK Perusahaan">
                    </div>
                    <div>
                        <label for="employee_id" class="block text-sm font-medium text-gray-700 mb-2">
                            Employee ID <span class="text-red-500">*</span>
                        </label>
                        <input type="text" id="employee_id" name="employee_id" required readonly
                               class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-dark-leaf focus:border-dark-leaf bg-gray-100"
                               placeholder="Otomatis terisi dari NIK">
                    </div>
                    <div>
                        <label for="full_name" class="block text-sm font-medium text-gray-700 mb-2">
                            Nama Lengkap <span class="text-red-500">*</span>
                        </label>
                        <input type="text" id="full_name" name="full_name" required
                               class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-dark-leaf focus:border-dark-leaf"
                               placeholder="Nama lengkap">
                    </div>
                    <div>
                        <label for="password" class="block text-sm font-medium text-gray-700 mb-2">
                            Password <span class="text-red-500">*</span>
                        </label>
                        <input type="password" id="password" name="password" required
                               class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-dark-leaf focus:border-dark-leaf"
                               placeholder="Password">
                    </div>
                    <div>
                        <label for="branch_name" class="block text-sm font-medium text-gray-700 mb-2">
                            Nama Cabang <span class="text-red-500">*</span>
                        </label>
                        <input type="text" id="branch_name" name="branch_name" required
                               class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-dark-leaf focus:border-dark-leaf"
                               placeholder="Nama cabang">
                    </div>
                    <div>
                        <label for="organization" class="block text-sm font-medium text-gray-700 mb-2">
                            Organisasi <span class="text-red-500">*</span>
                        </label>
                        <input type="text" id="organization" name="organization" required
                               class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-dark-leaf focus:border-dark-leaf"
                               placeholder="Nama organisasi">
                    </div>
                    <div class="md:col-span-2">
                        <label for="jabatan" class="block text-sm font-medium text-gray-700 mb-2">
                            Jabatan <span class="text-red-500">*</span>
                        </label>
                        <input type="text" id="jabatan" name="jabatan" required
                               class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-dark-leaf focus:border-dark-leaf"
                               placeholder="Jabatan">
                    </div>
                </div>
                <div class="flex space-x-4">
                    <button type="submit" class="bg-dark-leaf hover:bg-green-600 text-white px-6 py-3 rounded-lg transition duration-200 font-semibold">
                        Tambah <?php echo ucfirst($type); ?>
                    </button>
                    <a href="users.php" class="bg-medium-gray hover:bg-gray-600 text-white px-6 py-3 rounded-lg transition duration-200 font-semibold">
                        Batal
                    </a>
                </div>
            </form>
            <?php endif; ?>
        </div>
    </div>

    <script>
        // Form validation
        document.querySelector('form').addEventListener('submit', function(e) {
            const requiredFields = document.querySelectorAll('input[required], select[required]');
            let hasErrors = false;
            
            requiredFields.forEach(field => {
                if (!field.value.trim()) {
                    field.classList.add('border-red-500');
                    hasErrors = true;
                } else {
                    field.classList.remove('border-red-500');
                }
            });
            
            if (hasErrors) {
                e.preventDefault();
                alert('Mohon lengkapi semua field yang wajib diisi!');
                return false;
            }
        });
        
        // Auto-fill employee ID with NIK value
        <?php if ($type != 'asset'): ?>
        document.getElementById('nik').addEventListener('input', function() {
            const nikValue = this.value;
            const employeeIdField = document.getElementById('employee_id');
            employeeIdField.value = nikValue;
        });
        <?php endif; ?>
    </script>
</body>
</html>