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

$id = (int)$_GET['id'];
$type = $_GET['type'] ?? 'asset';
$message = '';
$message_type = '';
$data = null;

// Get existing data
try {
    if ($type == 'asset') {
        $stmt = $pdo->prepare("SELECT * FROM assets WHERE id = ?");
        $stmt->execute([$id]);
        $data = $stmt->fetch();
        $back_url = 'assets.php';
    } elseif ($type == 'admin') {
        $stmt = $pdo->prepare("SELECT * FROM admins WHERE id = ?");
        $stmt->execute([$id]);
        $data = $stmt->fetch();
        $back_url = 'users.php';
    } elseif ($type == 'borrower') {
        $stmt = $pdo->prepare("SELECT * FROM borrowers WHERE id = ?");
        $stmt->execute([$id]);
        $data = $stmt->fetch();
        $back_url = 'users.php';
    }
    
    if (!$data) {
        header("Location: dashboard.php");
        exit();
    }
} catch (Exception $e) {
    header("Location: dashboard.php");
    exit();
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    try {
        if ($type == 'asset') {
            // Update 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']);
            $status_borrower = sanitize($_POST['status_borrower']);
            
            // Check if asset number already exists (excluding current asset)
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM assets WHERE asset_number = ? AND id != ?");
            $stmt->execute([$asset_number, $id]);
            
            if ($stmt->fetchColumn() > 0) {
                $message = 'Asset number sudah ada! Gunakan nomor yang berbeda.';
                $message_type = 'error';
            } else {
                $stmt = $pdo->prepare("
                    UPDATE assets SET 
                    asset_number = ?, asset_name = ?, asset_category = ?, 
                    barcode_number = ?, kode_material_sap = ?, description = ?, 
                    status_borrower = ?, updated_at = NOW()
                    WHERE id = ?
                ");
                $stmt->execute([$asset_number, $asset_name, $asset_category, $barcode_number, $kode_material_sap, $description, $status_borrower, $id]);
                
                $message = 'Asset berhasil diupdate!';
                $message_type = 'success';
                
                // Refresh data
                $stmt = $pdo->prepare("SELECT * FROM assets WHERE id = ?");
                $stmt->execute([$id]);
                $data = $stmt->fetch();
            }
            
        } elseif ($type == 'admin' || $type == 'borrower') {
            // Update User - FIXED: Removed NIK references
            $employee_id = sanitize($_POST['employee_id']);
            $full_name = sanitize($_POST['full_name']);
            $branch_name = sanitize($_POST['branch_name']);
            $organization = sanitize($_POST['organization']);
            $jabatan = sanitize($_POST['jabatan']);
            $is_active = (int)$_POST['is_active'];
            
            $table = $type == 'admin' ? 'admins' : 'borrowers';
            
            // Check if employee_id already exists (excluding current user)
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM $table WHERE employee_id = ? AND id != ?");
            $stmt->execute([$employee_id, $id]);
            
            if ($stmt->fetchColumn() > 0) {
                $message = 'Employee ID sudah ada!';
                $message_type = 'error';
            } else {
                // Check if password should be updated
                if (!empty($_POST['new_password'])) {
                    $password_hash = hash('sha256', $_POST['new_password']);
                    $stmt = $pdo->prepare("
                        UPDATE $table SET 
                        employee_id = ?, full_name = ?, branch_name = ?, 
                        organization = ?, jabatan = ?, is_active = ?, 
                        password = ?, updated_at = NOW()
                        WHERE id = ?
                    ");
                    $stmt->execute([$employee_id, $full_name, $branch_name, $organization, $jabatan, $is_active, $password_hash, $id]);
                } else {
                    $stmt = $pdo->prepare("
                        UPDATE $table SET 
                        employee_id = ?, full_name = ?, branch_name = ?, 
                        organization = ?, jabatan = ?, is_active = ?, updated_at = NOW()
                        WHERE id = ?
                    ");
                    $stmt->execute([$employee_id, $full_name, $branch_name, $organization, $jabatan, $is_active, $id]);
                }
                
                $message = ucfirst($type) . ' berhasil diupdate!';
                $message_type = 'success';
                
                // Refresh data
                $stmt = $pdo->prepare("SELECT * FROM $table WHERE id = ?");
                $stmt->execute([$id]);
                $data = $stmt->fetch();
            }
        }
    } catch (Exception $e) {
        $message = 'Terjadi kesalahan: ' . $e->getMessage();
        $message_type = 'error';
    }
}

// Page titles
$page_info = [
    'asset' => 'Edit Asset',
    'admin' => 'Edit Admin',
    'borrower' => 'Edit Borrower'
];
?>

<!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]; ?> - 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 $back_url; ?>" 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]; ?></h1>
                        <p class="text-sm text-medium-gray">Edit data existing</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">
        <!-- 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
                               value="<?php echo htmlspecialchars($data['asset_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">
                    </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
                               value="<?php echo htmlspecialchars($data['asset_name']); ?>"
                               class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-dark-leaf focus:border-dark-leaf">
                    </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" <?php echo $data['asset_category'] == 'Electronics' ? 'selected' : ''; ?>>Electronics</option>
                            <option value="Tools" <?php echo $data['asset_category'] == 'Tools' ? 'selected' : ''; ?>>Tools</option>
                            <option value="Furniture" <?php echo $data['asset_category'] == 'Furniture' ? 'selected' : ''; ?>>Furniture</option>
                            <option value="Vehicle" <?php echo $data['asset_category'] == 'Vehicle' ? 'selected' : ''; ?>>Vehicle</option>
                            <option value="Others" <?php echo $data['asset_category'] == 'Others' ? 'selected' : ''; ?>>Others</option>
                        </select>
                    </div>
                    <div>
                        <label for="status_borrower" class="block text-sm font-medium text-gray-700 mb-2">
                            Status <span class="text-red-500">*</span>
                        </label>
                        <select id="status_borrower" name="status_borrower" 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="available" <?php echo $data['status_borrower'] == 'available' ? 'selected' : ''; ?>>Available</option>
                            <option value="borrowed" <?php echo $data['status_borrower'] == 'borrowed' ? 'selected' : ''; ?>>Borrowed</option>
                            <option value="maintenance" <?php echo $data['status_borrower'] == 'maintenance' ? 'selected' : ''; ?>>Maintenance</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"
                               value="<?php echo htmlspecialchars($data['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">
                    </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"
                               value="<?php echo htmlspecialchars($data['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">
                    </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"><?php echo htmlspecialchars($data['description']); ?></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">
                        Update 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 - FIXED: Removed NIK field -->
            <form method="POST" class="space-y-6">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <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
                               value="<?php echo htmlspecialchars($data['employee_id']); ?>"
                               class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-dark-leaf focus:border-dark-leaf">
                    </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
                               value="<?php echo htmlspecialchars($data['full_name']); ?>"
                               class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-dark-leaf focus:border-dark-leaf">
                    </div>
                    <div>
                        <label for="is_active" class="block text-sm font-medium text-gray-700 mb-2">
                            Status Aktif <span class="text-red-500">*</span>
                        </label>
                        <select id="is_active" name="is_active" 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="1" <?php echo $data['is_active'] == 1 ? 'selected' : ''; ?>>Aktif</option>
                            <option value="0" <?php echo $data['is_active'] == 0 ? 'selected' : ''; ?>>Non-Aktif</option>
                        </select>
                    </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
                               value="<?php echo htmlspecialchars($data['branch_name']); ?>"
                               class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-dark-leaf focus:border-dark-leaf">
                    </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
                               value="<?php echo htmlspecialchars($data['organization']); ?>"
                               class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-dark-leaf focus:border-dark-leaf">
                    </div>
                    <div>
                        <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
                               value="<?php echo htmlspecialchars($data['jabatan']); ?>"
                               class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-dark-leaf focus:border-dark-leaf">
                    </div>
                    <div class="md:col-span-2">
                        <label for="new_password" class="block text-sm font-medium text-gray-700 mb-2">
                            Password Baru (Kosongkan jika tidak ingin mengubah)
                        </label>
                        <input type="password" id="new_password" name="new_password"
                               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 baru (opsional)">
                    </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">
                        Update <?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>

        <!-- Additional Info -->
        <div class="mt-6 bg-white rounded-xl shadow-lg p-6">
            <h3 class="text-lg font-semibold text-gray-800 mb-4">Informasi</h3>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
                <div>
                    <p class="text-medium-gray">Created:</p>
                    <p class="font-medium text-gray-800"><?php echo date('d F Y, H:i', strtotime($data['created_at'])); ?></p>
                </div>
                <div>
                    <p class="text-medium-gray">Last Updated:</p>
                    <p class="font-medium text-gray-800"><?php echo date('d F Y, H:i', strtotime($data['updated_at'])); ?></p>
                </div>
            </div>
        </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;
            }
        });
    </script>
</body>
</html>