<?php
session_start();
if (empty($_SESSION['is_admin'])) { header('Location: login.php'); exit; }

$dataFile = __DIR__ . '/../data/products.json';
$products = [];
if (file_exists($dataFile)) { $products = json_decode(file_get_contents($dataFile), true) ?: []; }

$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = trim($_POST['title'] ?? '');
    $price = (float)($_POST['price'] ?? 0);
    $cat = trim($_POST['cat'] ?? '');
    $desc = trim($_POST['desc'] ?? '');
    $image = '';
    if (!empty($_FILES['image']['tmp_name'])) {
        $dest = __DIR__ . '/../pics_ecom/' . basename($_FILES['image']['name']);
        if (move_uploaded_file($_FILES['image']['tmp_name'], $dest)) {
            $image = 'pics_ecom/' . basename($_FILES['image']['name']);
        }
    }
    if ($title && $price) {
        $id = 1; foreach ($products as $p) if ($p['id'] >= $id) $id = $p['id'] + 1;
        $products[] = ['id'=>$id,'title'=>$title,'price'=>$price,'cat'=>$cat,'desc'=>$desc,'image'=>$image];
        file_put_contents($dataFile, json_encode($products, JSON_PRETTY_PRINT));
        header('Location: products.php'); exit;
    } else { $error = 'Title and price are required.'; }
}

?>
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>Add Product - Admin</title>
  <link rel="stylesheet" href="/ecom/styles.css">
</head>
<body>
<?php include __DIR__ . '/../header.php'; ?>
<main class="container">
  <h1>Add Product</h1>
  <?php if ($error) echo '<p class="muted">'.htmlspecialchars($error).'</p>'; ?>
  <form method="post" enctype="multipart/form-data" style="display:flex;flex-direction:column;gap:8px;max-width:600px;">
    <input name="title" placeholder="Title" required>
    <input name="price" placeholder="Price" required>
    <input name="cat" placeholder="Category">
    <textarea name="desc" placeholder="Description"></textarea>
    <label>Image (optional): <input type="file" name="image" accept="image/*"></label>
    <button class="btn" type="submit">Save Product</button>
  </form>
</main>
<?php include __DIR__ . '/../footer.php'; ?>
</body>
</html>
