<?php
session_start();

require_once __DIR__ . '/../../DataBase/koneksi.php';

// Cek login dan role
if (!isset($_SESSION['login']) || $_SESSION['login'] !== true) {
    header("Location: ../../index.html?error=session");
    exit;
}

if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'S') {
    header("Location: ../../index.html?error=unauthorized");
    exit;
}

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

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $kode_barang = trim($_POST['kode_barang']);
    $nama_barang = trim($_POST['nama_barang']);
    $id_kategori = $_POST['id_kategori'];
    $harga = $_POST['harga'];
    $stok = $_POST['stok'];
    $deskripsi = trim($_POST['deskripsi']);
    
    // Validasi
    if (empty($kode_barang) || empty($nama_barang) || empty($harga) || empty($stok)) {
        $error = "Kode barang, nama barang, harga, dan stok harus diisi!";
    } else {
        // Cek kode barang sudah ada
        $check = $conn->prepare("SELECT id_barang FROM barang WHERE kode_barang = ?");
        $check->bind_param("s", $kode_barang);
        $check->execute();
        
        if ($check->get_result()->num_rows > 0) {
            $error = "Kode barang sudah digunakan!";
        } else {
            // Insert barang baru
            $stmt = $conn->prepare("INSERT INTO barang (kode_barang, nama_barang, id_kategori, harga, stok, deskripsi) VALUES (?, ?, ?, ?, ?, ?)");
            $stmt->bind_param("ssiiss", $kode_barang, $nama_barang, $id_kategori, $harga, $stok, $deskripsi);
            
            if ($stmt->execute()) {
                $success = "Barang berhasil ditambahkan!";
                // Reset form
                $_POST = array();
            } else {
                $error = "Gagal menambahkan barang: " . $conn->error;
            }
        }
    }
}

// Get all categories
$categories = $conn->query("SELECT * FROM kategori ORDER BY nama_kategori ASC");

// Generate auto kode barang
$lastCode = $conn->query("SELECT kode_barang FROM barang ORDER BY id_barang DESC LIMIT 1");
$newCode = "BRG001";
if ($lastCode->num_rows > 0) {
    $last = $lastCode->fetch_assoc()['kode_barang'];
    $num = intval(substr($last, 3)) + 1;
    $newCode = "BRG" . str_pad($num, 3, "0", STR_PAD_LEFT);
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tambah Barang - Staff Aset</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Plus Jakarta Sans', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 900px;
            margin: 0 auto;
        }

        /* Header */
        .page-header {
            background: white;
            border-radius: 20px;
            padding: 30px 40px;
            margin-bottom: 30px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.1);
        }

        .page-header h1 {
            font-size: 32px;
            color: #1a202c;
            margin-bottom: 8px;
            font-weight: 800;
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .page-header p {
            color: #64748b;
            font-size: 16px;
        }

        /* Alert */
        .alert {
            padding: 16px 20px;
            border-radius: 12px;
            margin-bottom: 25px;
            display: flex;
            align-items: center;
            gap: 12px;
            animation: slideDown 0.3s ease;
        }

        @keyframes slideDown {
            from {
                opacity: 0;
                transform: translateY(-10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .alert-success {
            background: linear-gradient(135deg, #d1fae5 0%, #a7f3d0 100%);
            color: #065f46;
            border-left: 4px solid #10b981;
        }

        .alert-danger {
            background: linear-gradient(135deg, #fee2e2 0%, #fecaca 100%);
            color: #991b1b;
            border-left: 4px solid #dc2626;
        }

        /* Form Card */
        .form-card {
            background: white;
            border-radius: 20px;
            padding: 40px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.1);
            margin-bottom: 30px;
        }

        .form-section {
            margin-bottom: 30px;
        }

        .section-title {
            font-size: 18px;
            font-weight: 700;
            color: #1a202c;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid #f1f5f9;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .section-title i {
            color: #667eea;
        }

        .form-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 20px;
        }

        .form-group {
            display: flex;
            flex-direction: column;
        }

        .form-group.full {
            grid-column: 1 / -1;
        }

        .form-group label {
            font-size: 14px;
            font-weight: 600;
            color: #334155;
            margin-bottom: 8px;
            display: flex;
            align-items: center;
            gap: 5px;
        }

        .required {
            color: #ef4444;
        }

        .form-control {
            padding: 12px 16px;
            border: 2px solid #e2e8f0;
            border-radius: 12px;
            font-size: 14px;
            font-family: 'Plus Jakarta Sans', sans-serif;
            transition: all 0.3s;
        }

        .form-control:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.1);
        }

        textarea.form-control {
            resize: vertical;
            min-height: 100px;
        }

        .input-icon {
            position: relative;
        }

        .input-icon i {
            position: absolute;
            left: 16px;
            top: 50%;
            transform: translateY(-50%);
            color: #94a3b8;
        }

        .input-icon .form-control {
            padding-left: 45px;
        }

        .hint-text {
            font-size: 12px;
            color: #64748b;
            margin-top: 5px;
        }

        .btn {
            padding: 14px 28px;
            border: none;
            border-radius: 12px;
            cursor: pointer;
            font-size: 15px;
            font-weight: 600;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 10px;
            transition: all 0.3s;
            font-family: 'Plus Jakarta Sans', sans-serif;
        }

        .btn-primary {
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
            color: white;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(16, 185, 129, 0.4);
        }

        .btn-secondary {
            background: #f1f5f9;
            color: #475569;
        }

        .btn-secondary:hover {
            background: #e2e8f0;
        }

        .btn-outline {
            background: transparent;
            color: #667eea;
            border: 2px solid #667eea;
        }

        .btn-outline:hover {
            background: #667eea;
            color: white;
        }

        .form-actions {
            display: flex;
            gap: 15px;
            justify-content: flex-end;
            padding-top: 20px;
            border-top: 2px solid #f1f5f9;
        }

        .code-display {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 15px 20px;
            border-radius: 12px;
            font-size: 18px;
            font-weight: 700;
            text-align: center;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
        }

        @media (max-width: 768px) {
            body {
                padding: 10px;
            }

            .page-header, .form-card {
                padding: 20px;
            }

            .page-header h1 {
                font-size: 24px;
            }

            .form-grid {
                grid-template-columns: 1fr;
            }

            .form-actions {
                flex-direction: column-reverse;
            }

            .btn {
                width: 100%;
                justify-content: center;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- Page Header -->
        <div class="page-header">
            <h1>
                <i class="fas fa-plus-circle"></i>
                Tambah Barang Baru
            </h1>
            <p>Masukkan informasi barang yang akan ditambahkan ke inventory</p>
        </div>

        <!-- Alerts -->
        <?php if (!empty($success)): ?>
        <div class="alert alert-success">
            <i class="fas fa-check-circle"></i>
            <?php echo $success; ?>
        </div>
        <?php endif; ?>

        <?php if (!empty($error)): ?>
        <div class="alert alert-danger">
            <i class="fas fa-exclamation-circle"></i>
            <?php echo $error; ?>
        </div>
        <?php endif; ?>

        <!-- Form Card -->
        <form method="POST" action="">
            <div class="form-card">
                <!-- Kode Barang Auto -->
                <div class="code-display">
                    <i class="fas fa-barcode"></i>
                    Kode Barang: <?php echo $newCode; ?>
                </div>

                <!-- Informasi Dasar -->
                <div class="form-section">
                    <div class="section-title">
                        <i class="fas fa-info-circle"></i>
                        Informasi Dasar
                    </div>
                    <div class="form-grid">
                        <div class="form-group">
                            <label>
                                Kode Barang <span class="required">*</span>
                            </label>
                            <div class="input-icon">
                                <i class="fas fa-barcode"></i>
                                <input type="text" name="kode_barang" class="form-control" 
                                       value="<?php echo isset($_POST['kode_barang']) ? htmlspecialchars($_POST['kode_barang']) : $newCode; ?>" 
                                       required>
                            </div>
                            <span class="hint-text">Kode unik untuk identifikasi barang</span>
                        </div>

                        <div class="form-group">
                            <label>
                                Kategori <span class="required">*</span>
                            </label>
                            <div class="input-icon">
                                <i class="fas fa-tag"></i>
                                <select name="id_kategori" class="form-control" required style="padding-left: 45px;">
                                    <option value="">Pilih Kategori</option>
                                    <?php 
                                    $categories->data_seek(0);
                                    while ($cat = $categories->fetch_assoc()): 
                                    ?>
                                        <option value="<?php echo $cat['id_kategori']; ?>"
                                                <?php echo (isset($_POST['id_kategori']) && $_POST['id_kategori'] == $cat['id_kategori']) ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($cat['nama_kategori']); ?>
                                        </option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                        </div>

                        <div class="form-group full">
                            <label>
                                Nama Barang <span class="required">*</span>
                            </label>
                            <div class="input-icon">
                                <i class="fas fa-box"></i>
                                <input type="text" name="nama_barang" class="form-control" 
                                       value="<?php echo isset($_POST['nama_barang']) ? htmlspecialchars($_POST['nama_barang']) : ''; ?>" 
                                       placeholder="Contoh: Laptop ASUS ROG Strix G15" required>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Informasi Stok & Harga -->
                <div class="form-section">
                    <div class="section-title">
                        <i class="fas fa-dollar-sign"></i>
                        Stok & Harga
                    </div>
                    <div class="form-grid">
                        <div class="form-group">
                            <label>
                                Stok Awal <span class="required">*</span>
                            </label>
                            <div class="input-icon">
                                <i class="fas fa-cubes"></i>
                                <input type="number" name="stok" class="form-control" 
                                       value="<?php echo isset($_POST['stok']) ? htmlspecialchars($_POST['stok']) : '0'; ?>" 
                                       min="0" required>
                            </div>
                            <span class="hint-text">Jumlah stok awal barang</span>
                        </div>

                        <div class="form-group">
                            <label>
                                Harga Satuan (Rp) <span class="required">*</span>
                            </label>
                            <div class="input-icon">
                                <i class="fas fa-money-bill-wave"></i>
                                <input type="number" name="harga" class="form-control" 
                                       value="<?php echo isset($_POST['harga']) ? htmlspecialchars($_POST['harga']) : ''; ?>" 
                                       min="0" step="0.01" required>
                            </div>
                            <span class="hint-text">Harga per unit barang</span>
                        </div>
                    </div>
                </div>

                <!-- Deskripsi -->
                <div class="form-section">
                    <div class="section-title">
                        <i class="fas fa-file-alt"></i>
                        Deskripsi
                    </div>
                    <div class="form-group">
                        <label>Deskripsi Barang</label>
                        <textarea name="deskripsi" class="form-control" 
                                  placeholder="Masukkan deskripsi detail barang (opsional)..."><?php echo isset($_POST['deskripsi']) ? htmlspecialchars($_POST['deskripsi']) : ''; ?></textarea>
                        <span class="hint-text">Informasi tambahan tentang barang (spesifikasi, kondisi, dll)</span>
                    </div>
                </div>

                <!-- Form Actions -->
                <div class="form-actions">
                    <a href="dashboard_staff.php" class="btn btn-secondary">
                        <i class="fas fa-times"></i> Batal
                    </a>
                    <button type="reset" class="btn btn-outline">
                        <i class="fas fa-redo"></i> Reset
                    </button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save"></i> Simpan Barang
                    </button>
                </div>
            </div>
        </form>

        <!-- Quick Links -->
        <div style="display: flex; gap: 15px; justify-content: center;">
            <a href="inventory.php" class="btn btn-outline">
                <i class="fas fa-list"></i> Lihat Inventory
            </a>
            <a href="barang_masuk.php" class="btn btn-outline">
                <i class="fas fa-arrow-down"></i> Input Barang Masuk
            </a>
        </div>
    </div>
</body>
</html>