<?php
require_once '../config/db_config.php';
require_once '../models/Product.php';
session_start();

if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    header('Location: login.php');
    exit;
}

$db = getDbConnection();

// Check if database connection is available
if ($db === null) {
    die("Koneksi database gagal. Silakan coba lagi nanti atau hubungi administrator.");
}

$products = [];
$error = '';

// --- Tambah Produk Logic (dari add_product.php) ---
$success_message = '';
$error_message = '';
$name = $description = '';
$price = $stock = 0;
$is_active = 1;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_product'])) {
    $name = trim($_POST['name']);
    $description = trim($_POST['description']);
    $price = (float) $_POST['price'];
    $stock = (int) $_POST['stock'];
    $is_active = isset($_POST['is_active']) ? 1 : 0;

    if (empty($name) || empty($description) || $price <= 0) {
        $error_message = "Silakan isi semua field yang diperlukan";
    } else {
        $image_path = '';
        if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
            $upload_dir = '../assets/';
            if (!file_exists($upload_dir)) {
                mkdir($upload_dir, 0777, true);
            }
            $file_extension = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
            $file_name = 'product_' . time() . '_' . rand(1000, 9999) . '.' . $file_extension;
            $target_file = $upload_dir . $file_name;
            if (move_uploaded_file($_FILES['image']['tmp_name'], $target_file)) {
                $image_path = 'assets/' . $file_name;
            } else {
                $error_message = "Gagal mengunggah gambar";
            }
        } else {
            $image_path = 'assets/default-product.jpg';
        }
        if (empty($error_message)) {
            try {
                $product = new Product();
                $product->name = $name;
                $product->description = $description;
                $product->price = $price;
                $product->stock = $stock;
                $product->image = $image_path;
                $product->is_active = $is_active;
                if ($product->create()) {
                    $success_message = "Produk berhasil ditambahkan";
                    $name = $description = '';
                    $price = $stock = 0;
                    $is_active = 1;
                } else {
                    $error_message = "Gagal menyimpan produk";
                }
            } catch (Exception $e) {
                $error_message = "Error: " . $e->getMessage();
            }
        }
    }
}
// --- END Tambah Produk Logic ---

try {
    $stmt = $db->query("SELECT * FROM products ORDER BY product_id DESC");
    $products = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $sold = [];
    $stmt2 = $db->query("SELECT product_id, SUM(quantity) as sold_qty FROM order_items GROUP BY product_id");
    foreach ($stmt2->fetchAll(PDO::FETCH_ASSOC) as $row) {
        $sold[$row['product_id']] = $row['sold_qty'];
    }
} catch (PDOException $e) {
    error_log("Admin listProduct database error: " . $e->getMessage());
    $error = 'Terjadi kesalahan sistem. Silakan coba lagi nanti.';
}

function formatRupiah($amount) {
    return 'Rp ' . number_format($amount, 0, ',', '.');
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Daftar Produk - Admin</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
</head>
<body class="bg-light d-flex flex-column min-vh-100">
    <div class="container-fluid flex-grow-1">
        <div class="row min-vh-100">
            <div class="col-lg-2 bg-dark text-white p-0">
                <?php include 'admin_sidebar.php'; ?>
            </div>
            <div class="col-lg-10 p-4">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h1 class="h3 fw-bold text-secondary">Daftar Produk</h1>
                    <button type="button" class="btn btn-success" onclick="openModal()"><i class="fas fa-plus me-2"></i>Tambah Produk</button>
                </div>
                <?php if (!empty($success_message)): ?>
                    <div class="alert alert-success" role="alert"><?php echo $success_message; ?></div>
                <?php endif; ?>
                <?php if (!empty($error_message)): ?>
                    <div class="alert alert-danger" role="alert"><?php echo $error_message; ?></div>
                <?php endif; ?>
                <!-- Modal Tambah Produk -->
                <div id="addProductModal" class="modal" style="display: none; position: fixed; z-index: 1050; left: 0; top: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.5);">
                  <div class="modal-dialog modal-dialog-centered">
                    <div class="modal-content">
                      <div class="modal-header">
                        <h5 class="modal-title">Tambah Produk Baru</h5>
                        <button type="button" class="btn-close" onclick="closeModal()" aria-label="Close"></button>
                      </div>
                      <form action="listProduct.php" method="POST" enctype="multipart/form-data">
                        <input type="hidden" name="add_product" value="1">
                        <div class="modal-body">
                          <div class="row g-3">
                            <div class="col-md-6">
                              <label for="name" class="form-label">Nama Produk</label>
                              <input type="text" name="name" id="name" value="<?php echo htmlspecialchars($name ?? ''); ?>" class="form-control" required>
                            </div>
                            <div class="col-md-6">
                              <label for="price" class="form-label">Harga (Rp)</label>
                              <input type="number" name="price" id="price" value="<?php echo $price ?? 0; ?>" class="form-control" required min="0">
                            </div>
                            <div class="col-12">
                              <label for="description" class="form-label">Deskripsi</label>
                              <textarea name="description" id="description" rows="3" class="form-control" required><?php echo htmlspecialchars($description ?? ''); ?></textarea>
                            </div>
                            <div class="col-md-6">
                              <label for="stock" class="form-label">Stok</label>
                              <input type="number" name="stock" id="stock" value="<?php echo $stock ?? 0; ?>" class="form-control" required min="0">
                            </div>
                            <div class="col-md-6">
                              <label for="image" class="form-label">Gambar Produk</label>
                              <input type="file" name="image" id="image" accept="image/*" class="form-control">
                            </div>
                            <div class="col-12">
                              <div class="form-check">
                                <input type="checkbox" name="is_active" id="is_active" class="form-check-input" <?php echo ($is_active ? 'checked' : ''); ?>>
                                <label for="is_active" class="form-check-label">Produk Aktif</label>
                              </div>
                            </div>
                          </div>
                        </div>
                        <div class="modal-footer">
                          <button type="button" class="btn btn-secondary" onclick="closeModal()">Batal</button>
                          <button type="submit" class="btn btn-success"><i class="fas fa-save me-2"></i>Simpan Produk</button>
                        </div>
                      </form>
                    </div>
                  </div>
                </div>
                <!-- END Modal Tambah Produk -->
                <div class="card shadow mb-4">
                  <div class="card-body">
                    <div class="table-responsive">
                      <table class="table table-bordered align-middle">
                        <thead class="table-light">
                          <tr>
                            <th>Nama & Deskripsi</th>
                            <th>Harga</th>
                            <th>Stok</th>
                            <th>Terjual</th>
                            <th>Gambar</th>
                            <th>Aksi</th>
                          </tr>
                        </thead>
                        <tbody>
                          <?php foreach ($products as $product): ?>
                          <tr>
                            <td>
                              <div class="fw-semibold mb-1"><?php echo htmlspecialchars($product['name']); ?></div>
                              <div class="text-muted small" style="white-space:pre-line"><?php echo nl2br(htmlspecialchars($product['description'])); ?></div>
                            </td>
                            <td><?php echo formatRupiah($product['price']); ?></td>
                            <td><?php echo $product['stock']; ?></td>
                            <td><?php echo $sold[$product['product_id']] ?? 0; ?></td>
                            <td>
                              <?php if (!empty($product['image'])): ?>
                                <img src="../<?php echo htmlspecialchars($product['image']); ?>" class="img-fluid rounded" style="max-width:60px;max-height:60px;object-fit:contain;" alt="Gambar Produk">
                              <?php else: ?>
                                <span class="text-muted">Tidak ada gambar</span>
                              <?php endif; ?>
                            </td>
                            <td>
                              <a href="edit_product.php?id=<?php echo $product['product_id']; ?>" class="btn btn-primary btn-sm me-1"><i class="fas fa-edit"></i> Edit</a>
                              <a href="delete_product.php?id=<?php echo $product['product_id']; ?>" class="btn btn-danger btn-sm" onclick="return confirm('Yakin ingin menghapus produk ini?');"><i class="fas fa-trash"></i> Hapus</a>
                            </td>
                          </tr>
                          <?php endforeach; ?>
                          <?php if (empty($products)): ?>
                          <tr>
                            <td colspan="7" class="text-center">Tidak ada produk yang tersedia.</td>
                          </tr>
                          <?php endif; ?>
                        </tbody>
                      </table>
                    </div>
                  </div>
                </div>
            </div>
        </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
      // Modal functions
      function openModal() {
        document.getElementById('addProductModal').style.display = 'block';
        document.body.style.overflow = 'hidden'; // Prevent background scrolling
      }
      
      function closeModal() {
        document.getElementById('addProductModal').style.display = 'none';
        document.body.style.overflow = 'auto'; // Restore scrolling
        // Reset form
        const form = document.querySelector('#addProductModal form');
        if (form) {
          form.reset();
        }
      }
      
      // Close modal when clicking outside
      document.addEventListener('DOMContentLoaded', function() {
        const modal = document.getElementById('addProductModal');
        modal.addEventListener('click', function(e) {
          if (e.target === modal) {
            closeModal();
          }
        });
        
        // Close modal with Escape key
        document.addEventListener('keydown', function(e) {
          if (e.key === 'Escape' && modal.style.display === 'block') {
            closeModal();
          }
        });
      });
    </script>
</body>
</html>
