<?php
// admin/products.php - Product CRUD Management
require_once 'header.php';

$action = isset($_GET['action']) ? $_GET['action'] : 'list';
$error = '';
$success = '';

// Load active products list from MySQL
$products = array();
try {
    $db = get_db_connection();
    if ($db) {
        $stmt = $db->query("SELECT * FROM products");
        while ($row = $stmt->fetch()) {
            $row['specs'] = json_decode($row['specs'], true) ?: array();
            $row['thai_specs'] = json_decode($row['thai_specs'], true) ?: array();
            $products[$row['id']] = $row;
        }
    }
} catch (Exception $e) {
    error_log("Admin failed to load products: " . $e->getMessage());
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 1. Process Add/Edit form submission
    if ($action === 'add' || $action === 'edit') {
        $id = isset($_POST['id']) ? trim($_POST['id']) : '';
        if ($action === 'add') {
            // Generate clean ID from name
            $name_slug = preg_replace('/[^a-z0-9_-]/', '', strtolower(str_replace(' ', '-', $_POST['name'])));
            $id = $name_slug ?: uniqid('tee-');
            if (isset($products[$id])) {
                $id = $id . '-' . time();
            }
        }
        
        $name = isset($_POST['name']) ? trim($_POST['name']) : '';
        $thai_name = isset($_POST['thai_name']) ? trim($_POST['thai_name']) : '';
        $tier = isset($_POST['tier']) ? trim($_POST['tier']) : 'Basic';
        $price = isset($_POST['price']) ? floatval($_POST['price']) : 0.0;
        $tagline = isset($_POST['tagline']) ? trim($_POST['tagline']) : '';
        $thai_tagline = isset($_POST['thai_tagline']) ? trim($_POST['thai_tagline']) : '';
        $description = isset($_POST['description']) ? trim($_POST['description']) : '';
        $thai_description = isset($_POST['thai_description']) ? trim($_POST['thai_description']) : '';
        
        // Handle specifications (line-by-line input)
        $specs_raw = isset($_POST['specs']) ? trim($_POST['specs']) : '';
        $specs = array_filter(array_map('trim', explode("\n", $specs_raw)));
        
        $thai_specs_raw = isset($_POST['thai_specs']) ? trim($_POST['thai_specs']) : '';
        $thai_specs = array_filter(array_map('trim', explode("\n", $thai_specs_raw)));
        
        // Handle Image upload or URL
        $image_url = isset($_POST['image_url']) ? trim($_POST['image_url']) : '';
        if (isset($_FILES['image_file']) && $_FILES['image_file']['error'] === UPLOAD_ERR_OK) {
            $upload_dir = '../assets/uploads';
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0777, true);
            }
            $ext = pathinfo($_FILES['image_file']['name'], PATHINFO_EXTENSION);
            $filename = uniqid('img_') . '.' . $ext;
            $target_file = $upload_dir . '/' . $filename;
            if (move_uploaded_file($_FILES['image_file']['tmp_name'], $target_file)) {
                $image_url = 'assets/uploads/' . $filename;
            } else {
                $error = 'Failed to move uploaded image.';
            }
        }
        
        if (empty($name) || $price <= 0) {
            $error = 'Product Name and a positive Base Price are required.';
        }
        
        if (empty($error)) {
            $product_data = array(
                'id' => $id,
                'name' => $name,
                'thai_name' => $thai_name,
                'tier' => $tier,
                'price' => $price,
                'tagline' => $tagline,
                'thai_tagline' => $thai_tagline,
                'description' => $description,
                'thai_description' => $thai_description,
                'image_url' => $image_url,
                'specs' => array_values($specs),
                'thai_specs' => array_values($thai_specs)
            );
            
            try {
                $db = get_db_connection();
                if ($db) {
                    if ($action === 'add') {
                        $stmt = $db->prepare("INSERT INTO products (id, name, thai_name, tier, price, tagline, thai_tagline, description, thai_description, image_url, specs, thai_specs) 
                                              VALUES (:id, :name, :thai_name, :tier, :price, :tagline, :thai_tagline, :description, :thai_description, :image_url, :specs, :thai_specs)");
                    } else {
                        $stmt = $db->prepare("UPDATE products SET name = :name, thai_name = :thai_name, tier = :tier, price = :price, tagline = :tagline, thai_tagline = :thai_tagline, description = :description, thai_description = :thai_description, image_url = :image_url, specs = :specs, thai_specs = :thai_specs 
                                              WHERE id = :id");
                    }
                    $stmt->execute(array(
                        'id' => $id,
                        'name' => $name,
                        'thai_name' => $thai_name,
                        'tier' => $tier,
                        'price' => $price,
                        'tagline' => $tagline,
                        'thai_tagline' => $thai_tagline,
                        'description' => $description,
                        'thai_description' => $thai_description,
                        'image_url' => $image_url,
                        'specs' => json_encode(array_values($specs), JSON_UNESCAPED_UNICODE),
                        'thai_specs' => json_encode(array_values($thai_specs), JSON_UNESCAPED_UNICODE)
                    ));
                    
                    $_SESSION['success_msg'] = ($action === 'add') ? 'Product created successfully.' : 'Product updated successfully.';
                    header('Location: products.php');
                    exit;
                }
            } catch (Exception $e) {
                $error = 'Database save failed: ' . $e->getMessage();
            }
        }
    }
}

// Handle Delete confirmation action
if ($action === 'delete') {
    $id = isset($_GET['id']) ? $_GET['id'] : '';
    if (isset($products[$id])) {
        if (isset($_GET['confirm']) && $_GET['confirm'] === 'yes') {
            try {
                $db = get_db_connection();
                if ($db) {
                    $stmt = $db->prepare("DELETE FROM products WHERE id = :id");
                    $stmt->execute(array('id' => $id));
                    $_SESSION['success_msg'] = 'Product deleted successfully.';
                    header('Location: products.php');
                    exit;
                }
            } catch (Exception $e) {
                $error = 'Database delete failed: ' . $e->getMessage();
            }
        }
    }
}

$success = isset($_SESSION['success_msg']) ? $_SESSION['success_msg'] : '';
unset($_SESSION['success_msg']);
?>

<div class="container">
  
  <?php if ($success): ?>
    <div style="padding: 12px; background-color: rgba(0, 128, 0, 0.1); border: 1px solid rgba(0, 128, 0, 0.2); border-radius: 6px; font-size: 13px; margin-bottom: 24px; color: #34c759;">
      <?php echo htmlspecialchars($success); ?>
    </div>
  <?php endif; ?>

  <?php if ($error): ?>
    <div style="padding: 12px; background-color: rgba(255, 0, 0, 0.1); border: 1px solid rgba(255, 0, 0, 0.2); border-radius: 6px; font-size: 13px; margin-bottom: 24px; color: #ff3b30;">
      <?php echo htmlspecialchars($error); ?>
    </div>
  <?php endif; ?>

  <?php if ($action === 'list'): ?>
    <!-- 1. PRODUCT LIST VIEW -->
    <div class="admin-actions-bar">
      <div>
        <h1 style="font-size: 28px; font-weight: 600; letter-spacing: -0.02em;">Products</h1>
        <p style="color: var(--text-secondary); font-size: 14px;">Manage all product items, tier configuration, and pricing.</p>
      </div>
      <a href="products.php?action=add" class="btn btn-primary">+ Add Product</a>
    </div>

    <div class="card-glass">
      <div class="admin-table-container">
        <table class="admin-table">
          <thead>
            <tr>
              <th>Image</th>
              <th>Name</th>
              <th>Tier</th>
              <th>Base Price</th>
              <th>Tagline</th>
              <th style="text-align: right;">Actions</th>
            </tr>
          </thead>
          <tbody>
            <?php if (empty($products)): ?>
              <tr>
                <td colspan="6" style="text-align: center; color: var(--text-secondary); padding: 40px;">No products found in the catalog.</td>
              </tr>
            <?php else: ?>
              <?php foreach ($products as $id => $p): ?>
                <tr>
                  <td>
                    <img src="<?php echo htmlspecialchars($p['image_url'] ? '../' . $p['image_url'] : '../assets/images/default.jpg'); ?>" alt="" class="product-thumbnail" onerror="this.src='https://images.unsplash.com/photo-1521572267360-ee0c2909d518?auto=format&fit=crop&q=80&w=100';">
                  </td>
                  <td>
                    <strong><?php echo htmlspecialchars($p['name']); ?></strong><br>
                    <span style="font-family: 'Prompt'; font-size: 11px; color: var(--text-secondary);"><?php echo htmlspecialchars($p['thai_name']); ?></span>
                  </td>
                  <td>
                    <span class="badge-tier badge-<?php echo strtolower($p['tier']); ?>"><?php echo htmlspecialchars($p['tier']); ?></span>
                  </td>
                  <td>$<?php echo number_format($p['price'], 2); ?></td>
                  <td style="max-width: 240px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">
                    <?php echo htmlspecialchars($p['tagline']); ?>
                  </td>
                  <td style="text-align: right;">
                    <a href="products.php?action=edit&id=<?php echo urlencode($id); ?>" class="btn" style="padding: 4px 8px; font-size: 11px; margin-right: 4px;">Edit</a>
                    <a href="products.php?action=delete&id=<?php echo urlencode($id); ?>" class="btn" style="padding: 4px 8px; font-size: 11px; color: #ff3b30; border-color: rgba(255,59,48,0.3);">Delete</a>
                  </td>
                </tr>
              <?php endforeach; ?>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>

  <?php elseif ($action === 'add' || $action === 'edit'): ?>
    <!-- 2. ADD / EDIT PRODUCT VIEW -->
    <?php
    $id = isset($_GET['id']) ? $_GET['id'] : '';
    $p = ($action === 'edit' && isset($products[$id])) ? $products[$id] : array(
        'id' => '',
        'name' => '',
        'thai_name' => '',
        'tier' => 'Basic',
        'price' => 0.0,
        'tagline' => '',
        'thai_tagline' => '',
        'description' => '',
        'thai_description' => '',
        'image_url' => '',
        'specs' => array(),
        'thai_specs' => array()
    );
    ?>
    <div style="margin-bottom: 24px;">
      <a href="products.php" style="font-size: 13px; color: var(--text-secondary);">&larr; Back to Catalog</a>
      <h1 style="font-size: 28px; font-weight: 600; letter-spacing: -0.02em; margin-top: 8px;">
        <?php echo $action === 'add' ? 'Add Product' : 'Edit Product: ' . htmlspecialchars($p['name']); ?>
      </h1>
    </div>

    <div class="card-glass">
      <form action="products.php?action=<?php echo $action; ?><?php echo $action === 'edit' ? '&id=' . urlencode($id) : ''; ?>" method="POST" enctype="multipart/form-data">
        <input type="hidden" name="id" value="<?php echo htmlspecialchars($p['id']); ?>">
        
        <div class="form-grid-2">
          <div class="form-group">
            <label for="name">Product Name (English)</label>
            <input type="text" id="name" name="name" class="form-control" value="<?php echo htmlspecialchars($p['name']); ?>" required>
          </div>
          <div class="form-group">
            <label for="thai_name">Product Name (Thai) / ชื่อสินค้าภาษาไทย</label>
            <input type="text" id="thai_name" name="thai_name" class="form-control" value="<?php echo htmlspecialchars($p['thai_name']); ?>">
          </div>
        </div>

        <div class="form-grid-2">
          <div class="form-group">
            <label for="tier">Product Tier</label>
            <select id="tier" name="tier" class="form-control" style="background: var(--input-bg); color: var(--text-primary);">
              <option value="Basic" <?php echo $p['tier'] === 'Basic' ? 'selected' : ''; ?>>Basic Tier</option>
              <option value="Pro" <?php echo $p['tier'] === 'Pro' ? 'selected' : ''; ?>>Pro Tier</option>
              <option value="Luxury" <?php echo $p['tier'] === 'Luxury' ? 'selected' : ''; ?>>Luxury Tier</option>
            </select>
          </div>
          <div class="form-group">
            <label for="price">Base Price ($ USD)</label>
            <input type="number" step="0.01" min="0.01" id="price" name="price" class="form-control" value="<?php echo htmlspecialchars($p['price']); ?>" required>
          </div>
        </div>

        <div class="form-grid-2">
          <div class="form-group">
            <label for="tagline">Tagline (English)</label>
            <input type="text" id="tagline" name="tagline" class="form-control" value="<?php echo htmlspecialchars($p['tagline']); ?>">
          </div>
          <div class="form-group">
            <label for="thai_tagline">Tagline (Thai) / สโลแกนภาษาไทย</label>
            <input type="text" id="thai_tagline" name="thai_tagline" class="form-control" value="<?php echo htmlspecialchars($p['thai_tagline']); ?>">
          </div>
        </div>

        <div class="form-grid-2">
          <div class="form-group">
            <label for="description">Description (English)</label>
            <textarea id="description" name="description" class="form-control" rows="3" style="font-family: inherit; resize: vertical;"><?php echo htmlspecialchars($p['description']); ?></textarea>
          </div>
          <div class="form-group">
            <label for="thai_description">Description (Thai) / รายละเอียดภาษาไทย</label>
            <textarea id="thai_description" name="thai_description" class="form-control" rows="3" style="font-family: inherit; resize: vertical;"><?php echo htmlspecialchars($p['thai_description']); ?></textarea>
          </div>
        </div>

        <!-- Image settings -->
        <div class="form-grid-2" style="border-top: 1px solid var(--border-color); padding-top: 20px;">
          <div class="form-group">
            <label for="image_url">Product Image URL</label>
            <input type="text" id="image_url" name="image_url" class="form-control" value="<?php echo htmlspecialchars($p['image_url']); ?>" placeholder="https://example.com/image.jpg">
          </div>
          <div class="form-group">
            <label for="image_file">Upload Image File (Alternative)</label>
            <input type="file" id="image_file" name="image_file" class="form-control" accept="image/*">
          </div>
        </div>

        <!-- Specs lists -->
        <div class="form-grid-2" style="border-top: 1px solid var(--border-color); padding-top: 20px;">
          <div class="form-group">
            <label for="specs">Specifications (English, one per line)</label>
            <textarea id="specs" name="specs" class="form-control" rows="4" style="font-family: inherit; resize: vertical;" placeholder="100% Combed Cotton&#10;Mid-weight 180 GSM&#10;Preshrunk fabric"><?php echo htmlspecialchars(implode("\n", $p['specs'])); ?></textarea>
          </div>
          <div class="form-group">
            <label for="thai_specs">Specifications (Thai, one per line)</label>
            <textarea id="thai_specs" name="thai_specs" class="form-control" rows="4" style="font-family: inherit; resize: vertical;" placeholder="ผ้าคอตตอนคอมบ์ 100%&#10;ความหนาปานกลาง 180 GSM&#10;ผ่านการหดตัวล่วงหน้า"><?php echo htmlspecialchars(implode("\n", $p['thai_specs'])); ?></textarea>
          </div>
        </div>

        <div style="border-top: 1px solid var(--border-color); padding-top: 20px; display: flex; gap: 12px; justify-content: flex-end;">
          <a href="products.php" class="btn">Cancel</a>
          <button type="submit" class="btn btn-primary" style="padding: 10px 24px;">Save Product</button>
        </div>
      </form>
    </div>

  <?php elseif ($action === 'delete'): ?>
    <!-- 3. CONFIRM DELETE VIEW -->
    <?php $id = isset($_GET['id']) ? $_GET['id'] : ''; ?>
    <div class="card-glass" style="max-width: 500px; margin: 40px auto; text-align: center; padding: 40px 32px;">
      <div style="font-size: 40px; margin-bottom: 16px;">⚠️</div>
      <h2 style="font-size: 20px; font-weight: 600; margin-bottom: 8px;">Are you sure?</h2>
      <p style="font-size: 13px; color: var(--text-secondary); margin-bottom: 24px;">
        You are about to delete <strong><?php echo htmlspecialchars(isset($products[$id]) ? $products[$id]['name'] : ''); ?></strong>.<br>
        This product will immediately disappear from the live storefront.
      </p>
      <div style="display: flex; gap: 12px; justify-content: center;">
        <a href="products.php" class="btn">Cancel</a>
        <a href="products.php?action=delete&id=<?php echo urlencode($id); ?>&confirm=yes" class="btn btn-primary" style="background-color: #ff3b30; border-color: #ff3b30; color: #fff;">Yes, Delete Product</a>
      </div>
    </div>
  <?php endif; ?>

</div>

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