<?php
require_once '../../../config/database.php';
require_once '../../../config/auth.php';
require_once '../../../includes/header.php';
require_once '../../../includes/sidebar.php';
requireRole(['admin', 'super_admin']);

$db = getDB();
$error = '';
$success = '';

// Ambil data socket dan RAM types
$sockets = $db->query("SELECT * FROM socket_types ORDER BY manufacturer, name")->fetchAll();
$ram_types = $db->query("SELECT * FROM ram_types ORDER BY name")->fetchAll();

$id = $_GET['id'] ?? 0;
if (!$id) {
    header('Location: index.php');
    exit;
}

// Ambil data motherboard
$stmt = $db->prepare("
    SELECT m.*, ms.socket_id, ms.ram_type_id, ms.has_nvme, ms.max_ram_size, ms.max_ram_slots
    FROM motherboards m 
    LEFT JOIN motherboard_supports ms ON ms.motherboard_id = m.id
    WHERE m.id = ?
");
$stmt->execute([$id]);
$motherboard = $stmt->fetch();

if (!$motherboard) {
    header('Location: index.php');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = $_POST['name'] ?? '';
    $price = $_POST['price'] ?? 0;
    $compatibility = $_POST['compatibility'] ?? 0;
    $age = $_POST['age'] ?? 0;
    $socket_id = $_POST['socket_id'] ?? null;
    $ram_type_id = $_POST['ram_type_id'] ?? null;
    $has_nvme = isset($_POST['has_nvme']) ? 1 : 0;
    $max_ram_size = $_POST['max_ram_size'] ?? 0;
    $max_ram_slots = $_POST['max_ram_slots'] ?? 0;
    
    if (empty($name)) {
        $error = 'Nama motherboard harus diisi!';
    } elseif (!is_numeric($price) || $price <= 0) {
        $error = 'Harga harus berupa angka positif!';
    } elseif (!is_numeric($compatibility) || $compatibility < 1 || $compatibility > 10) {
        $error = 'Compatibility harus antara 1-10!';
    } elseif (!is_numeric($age) || $age < 0 || $age > 5) {
        $error = 'Age harus antara 0-5!';
    } elseif (empty($socket_id)) {
        $error = 'Socket harus dipilih!';
    } elseif (empty($ram_type_id)) {
        $error = 'RAM type harus dipilih!';
    } else {
        try {
            $db->beginTransaction();

            // Update motherboard
            $stmt = $db->prepare("UPDATE motherboards SET name = ?, price = ?, compatibility = ?, age = ? WHERE id = ?");
            $stmt->execute([$name, $price, $compatibility, $age, $id]);

            // Update or insert motherboard supports
            $stmt = $db->prepare("
                INSERT INTO motherboard_supports 
                (motherboard_id, socket_id, ram_type_id, has_nvme, max_ram_size, max_ram_slots)
                VALUES (?, ?, ?, ?, ?, ?)
                ON DUPLICATE KEY UPDATE
                socket_id = VALUES(socket_id),
                ram_type_id = VALUES(ram_type_id),
                has_nvme = VALUES(has_nvme),
                max_ram_size = VALUES(max_ram_size),
                max_ram_slots = VALUES(max_ram_slots)
            ");
            $stmt->execute([
                $id,
                $socket_id,
                $ram_type_id,
                $has_nvme,
                $max_ram_size,
                $max_ram_slots
            ]);

            $db->commit();
            $success = 'Data motherboard berhasil diupdate!';
            
            // Redirect setelah 1 detik
            
        } catch (PDOException $e) {
            $db->rollBack();
            $error = 'Terjadi kesalahan saat mengupdate data!';
        }
    }
}
?>

<!-- Form dan layout HTML sama seperti add.php, dengan value dari $motherboard -->
<div class="content-wrapper">
    <section class="content-header">
        <div class="container-fluid">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h1>Edit Motherboard</h1>
                </div>
            </div>
        </div>
    </section>

    <section class="content">
        <div class="container-fluid">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">Form Edit Motherboard</h3>
                </div>
                <div class="card-body">
                    <?php if ($error): ?>
                        <div class="alert alert-danger"><?php echo $error; ?></div>
                    <?php endif; ?>
                    <?php if ($success): ?>
                        <div class="alert alert-success"><?php echo $success; ?></div>
                    <?php endif; ?>

                    <form method="POST">
                        <div class="row">
                            <!-- Basic Information -->
                            <div class="col-md-6">
                                <div class="card card-primary">
                                    <div class="card-header">
                                        <h3 class="card-title">Informasi Dasar</h3>
                                    </div>
                                    <div class="card-body">
                                        <div class="form-group">
                                            <label for="name">Nama Motherboard</label>
                                            <input type="text" class="form-control" id="name" name="name" 
                                                   value="<?php echo htmlspecialchars($motherboard['name']); ?>" required>
                                        </div>

                                        <div class="form-group">
                                            <label for="price">Harga</label>
                                            <input type="number" class="form-control" id="price" name="price" 
                                                   value="<?php echo htmlspecialchars($motherboard['price']); ?>" min="0" required>
                                        </div>

                                        <div class="form-group">
                                            <label for="compatibility">Compatibility (1-10)</label>
                                            <input type="number" class="form-control" id="compatibility" name="compatibility" 
                                                   value="<?php echo htmlspecialchars($motherboard['compatibility']); ?>"
                                                   min="1" max="10" step="0.1" required>
                                        </div>

                                        <div class="form-group">
                                            <label for="age">Age (0-5)</label>
                                            <input type="number" class="form-control" id="age" name="age" 
                                                   value="<?php echo htmlspecialchars($motherboard['age']); ?>"
                                                   min="0" max="5" step="0.1" required>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Compatibility Information -->
                            <div class="col-md-6">
                                <div class="card card-success">
                                    <div class="card-header">
                                        <h3 class="card-title">Informasi Kompatibilitas</h3>
                                    </div>
                                    <div class="card-body">
                                        <div class="form-group">
                                            <label for="socket_id">Socket</label>
                                            <select class="form-control select2" id="socket_id" name="socket_id" required>
                                                <option value="">Pilih Socket</option>
                                                <?php foreach ($sockets as $socket): ?>
                                                    <option value="<?php echo $socket['id']; ?>" 
                                                            <?php echo ($motherboard['socket_id'] == $socket['id']) ? 'selected' : ''; ?>>
                                                        <?php echo htmlspecialchars($socket['name'] . ' (' . $socket['manufacturer'] . ' - ' . $socket['generation'] . ')'); ?>
                                                    </option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>

                                        <div class="form-group">
                                            <label for="ram_type_id">RAM Type</label>
                                            <select class="form-control select2" id="ram_type_id" name="ram_type_id" required>
                                                <option value="">Pilih RAM Type</option>
                                                <?php foreach ($ram_types as $type): ?>
                                                    <option value="<?php echo $type['id']; ?>" 
                                                            <?php echo ($motherboard['ram_type_id'] == $type['id']) ? 'selected' : ''; ?>>
                                                        <?php echo htmlspecialchars($type['name'] . ' (' . $type['speed_min'] . '-' . $type['speed_max'] . ' MHz)'); ?>
                                                    </option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>

                                        <div class="form-group">
                                            <label for="max_ram_size">Maximum RAM Size (GB)</label>
                                            <input type="number" class="form-control" id="max_ram_size" name="max_ram_size" 
                                                   value="<?php echo htmlspecialchars($motherboard['max_ram_size']); ?>" min="1" required>
                                        </div>

                                        <div class="form-group">
                                            <label for="max_ram_slots">RAM Slots</label>
                                            <input type="number" class="form-control" id="max_ram_slots" name="max_ram_slots" 
                                                   value="<?php echo htmlspecialchars($motherboard['max_ram_slots']); ?>" min="1" required>
                                        </div>

                                        <div class="form-group">
                                            <div class="custom-control custom-switch">
                                                <input type="checkbox" class="custom-control-input" id="has_nvme" name="has_nvme" 
                                                       <?php echo ($motherboard['has_nvme']) ? 'checked' : ''; ?>>
                                                <label class="custom-control-label" for="has_nvme">Support NVMe</label>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-12">
                                <button type="submit" class="btn btn-primary">Update</button>
                                <a href="index.php" class="btn btn-secondary">Kembali</a>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </section>
</div>

<?php require_once '../../../includes/footer.php'; ?>

<script>
$(function() {
    $('.select2').select2({
        theme: 'bootstrap4'
    });
});
</script>