<?php
require_once '../../includes/config.php';

// Check if admin is logged in
if (!isAdminLoggedIn()) {
    redirect(SITE_URL . 'admin/login.php');
}

$pageTitle = "Edit Produk";

// Get product ID from URL
$product_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if (!$product_id) {
    redirect(SITE_URL . 'admin/products/index.php');
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = sanitize($_POST['name']);
    $description = sanitize($_POST['description']);
    $price = (float)$_POST['price'];
    $stock = (int)$_POST['stock'];
    $category_id = (int)$_POST['category_id'] ?: null;
    
    // Validate input
    $errors = [];
    
    if (empty($name)) {
        $errors[] = "Nama produk tidak boleh kosong";
    }
    
    if ($price <= 0) {
        $errors[] = "Harga produk harus lebih dari 0";
    }
    
    if ($stock < 0) {
        $errors[] = "Stok tidak boleh kurang dari 0";
    }
    
    // Get current image path
    try {
        $conn = connectDB();
        $stmt = $conn->prepare("SELECT image_path FROM products WHERE product_id = :product_id");
        $stmt->bindParam(':product_id', $product_id);
        $stmt->execute();
        $current_image = $stmt->fetch(PDO::FETCH_ASSOC)['image_path'];
    } catch (PDOException $e) {
        $error = "Error: " . $e->getMessage();
    }
    
    // Handle file upload
    $image_path = $current_image;
    if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
        $upload_dir = '../../assets/img/products/';
        
        // Create directory if not exists
        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0755, true);
        }
        
        $filename = $_FILES['image']['name'];
        $tmp_name = $_FILES['image']['tmp_name'];
        $file_ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
        
        // Check if extension is allowed
        $allowed_exts = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
        if (!in_array($file_ext, $allowed_exts)) {
            $errors[] = "Format gambar tidak didukung. Format yang didukung: " . implode(', ', $allowed_exts);
        } else {
            // Generate unique filename
            $new_filename = time() . '_' . uniqid() . '.' . $file_ext;
            $dest_path = $upload_dir . $new_filename;
            
            // Move uploaded file
            if (move_uploaded_file($tmp_name, $dest_path)) {
                $image_path = 'assets/img/products/' . $new_filename;
                
                // Delete old image if exists
                if ($current_image && file_exists('../../' . $current_image)) {
                    unlink('../../' . $current_image);
                }
            } else {
                $errors[] = "Gagal mengupload gambar. Silahkan coba lagi.";
            }
        }
    }
    
    // If no errors, update the product
    if (empty($errors)) {
        try {
            $conn = connectDB();
            
            $stmt = $conn->prepare("UPDATE products SET name = :name, description = :description, price = :price, 
                                   stock = :stock, image_path = :image_path, category_id = :category_id 
                                   WHERE product_id = :product_id");
            $stmt->bindParam(':name', $name);
            $stmt->bindParam(':description', $description);
            $stmt->bindParam(':price', $price);
            $stmt->bindParam(':stock', $stock);
            $stmt->bindParam(':image_path', $image_path);
            $stmt->bindParam(':category_id', $category_id);
            $stmt->bindParam(':product_id', $product_id);
            $stmt->execute();
            
            $success = "Produk berhasil diperbarui";
            
            // Redirect back to products list after successful update
            redirect(SITE_URL . 'admin/products/index.php?success=updated');
            
        } catch (PDOException $e) {
            $error = "Error: " . $e->getMessage();
        }
    }
} else {
    // Fetch the product data
    try {
        $conn = connectDB();
        $stmt = $conn->prepare("SELECT * FROM products WHERE product_id = :product_id");
        $stmt->bindParam(':product_id', $product_id);
        $stmt->execute();
        
        $product = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$product) {
            redirect(SITE_URL . 'admin/products/index.php');
        }
        
        // Set variables for form
        $name = $product['name'];
        $description = $product['description'];
        $price = $product['price'];
        $stock = $product['stock'];
        $category_id = $product['category_id'];
        $image_path = $product['image_path'];
        
    } catch (PDOException $e) {
        $error = "Error: " . $e->getMessage();
    }
}

// Get categories for dropdown
try {
    $conn = connectDB();
    $stmt = $conn->query("SELECT * FROM categories ORDER BY name");
    $categories = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $error = "Error: " . $e->getMessage();
}

include '../header.php';
?>

<div class="admin-header">
    <h1>Edit Produk</h1>
    <div>
        <a href="index.php" class="btn btn-secondary"><i class="fas fa-arrow-left"></i> Kembali</a>
    </div>
</div>

<?php if (isset($success)): ?>
    <div class="success"><?php echo $success; ?></div>
<?php endif; ?>

<?php if (isset($error)): ?>
    <div class="error"><?php echo $error; ?></div>
<?php endif; ?>

<?php if (!empty($errors)): ?>
    <div class="error">
        <ul>
            <?php foreach ($errors as $err): ?>
                <li><?php echo $err; ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
<?php endif; ?>

<div class="admin-content-box">
    <form action="edit.php?id=<?php echo $product_id; ?>" method="post" class="admin-form" enctype="multipart/form-data">
        <div class="form-group">
            <label for="name">Nama Produk <span class="required">*</span></label>
            <input type="text" id="name" name="name" value="<?php echo $name ?? ''; ?>" required>
        </div>
        
        <div class="form-group">
            <label for="category_id">Kategori</label>
            <select id="category_id" name="category_id">
                <option value="">-- Pilih Kategori --</option>
                <?php foreach ($categories as $category): ?>
                    <option value="<?php echo $category['category_id']; ?>" <?php echo (isset($category_id) && $category_id == $category['category_id']) ? 'selected' : ''; ?>>
                        <?php echo $category['name']; ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        
        <div class="form-row">
            <div class="form-group half">
                <label for="price">Harga (Rp) <span class="required">*</span></label>
                <input type="number" id="price" name="price" min="0" step="100" value="<?php echo $price ?? 0; ?>" required>
            </div>
            
            <div class="form-group half">
                <label for="stock">Stok <span class="required">*</span></label>
                <input type="number" id="stock" name="stock" min="0" value="<?php echo $stock ?? 0; ?>" required>
            </div>
        </div>
        
        <div class="form-group">
            <label for="image">Gambar Produk</label>
            <?php if (!empty($image_path)): ?>
                <div class="current-image">
                    <p>Gambar Saat Ini:</p>
                    <img src="<?php echo SITE_URL . $image_path; ?>" alt="<?php echo $name; ?>" style="max-width: 200px; margin-bottom: 10px;">
                </div>
            <?php endif; ?>
            <input type="file" id="image" name="image" accept="image/*">
            <small>Format yang didukung: JPG, JPEG, PNG, GIF, WEBP. Ukuran maksimal: 2MB.</small>
            <small>Biarkan kosong jika tidak ingin mengubah gambar.</small>
        </div>
        
        <div class="form-group">
            <label for="description">Deskripsi Produk</label>
            <textarea id="description" name="description" rows="6"><?php echo $description ?? ''; ?></textarea>
            <small>Berikan deskripsi lengkap tentang produk.</small>
        </div>
        
        <div class="form-actions">
            <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Simpan Perubahan</button>
            <a href="index.php" class="btn btn-secondary">Batal</a>
        </div>
    </form>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Preview image before upload
    const imageInput = document.getElementById('image');
    
    imageInput.addEventListener('change', function() {
        const file = this.files[0];
        if (file) {
            const imgPreview = this.parentNode.querySelector('.image-preview');
            if (imgPreview) {
                imgPreview.remove();
            }
            
            const previewDiv = document.createElement('div');
            previewDiv.className = 'image-preview';
            
            const img = document.createElement('img');
            img.style.maxWidth = '200px';
            img.style.marginTop = '10px';
            img.src = URL.createObjectURL(file);
            
            const previewText = document.createElement('p');
            previewText.textContent = 'Gambar Baru:';
            
            previewDiv.appendChild(previewText);
            previewDiv.appendChild(img);
            
            // Insert after file input
            this.parentNode.insertBefore(previewDiv, this.nextSibling);
        }
    });
});
</script>

<?php include '../footer.php'; ?> 