<?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) ?: []; }

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$itemKey = null;
foreach ($products as $k=>$p) if ($p['id'] === $id) $itemKey = $k;
if ($itemKey === null) { header('Location: products.php'); exit; }

$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = trim($_POST['title'] ?? '');
    $price = (float)($_POST['price'] ?? 0);
    $cat = trim($_POST['cat'] ?? '');
    $desc = trim($_POST['desc'] ?? '');
    if (!empty($_FILES['image']['tmp_name'])) {
        $dest = __DIR__ . '/../pics_ecom/' . basename($_FILES['image']['name']);
        if (move_uploaded_file($_FILES['image']['tmp_name'], $dest)) {
            $products[$itemKey]['image'] = 'pics_ecom/' . basename($_FILES['image']['name']);
        }
    }
    $products[$itemKey]['title'] = $title;
    $products[$itemKey]['price'] = $price;
    $products[$itemKey]['cat'] = $cat;
    $products[$itemKey]['desc'] = $desc;
    file_put_contents($dataFile, json_encode($products, JSON_PRETTY_PRINT));
    header('Location: products.php'); exit;
}

$p = $products[$itemKey];
?>
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>Edit Product - Admin</title>
  <link rel="stylesheet" href="/ecom/styles.css">
</head>
<body>
<?php include __DIR__ . '/../header.php'; ?>
<main class="container">
  <h1>Edit 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" value="<?php echo htmlspecialchars($p['title']); ?>" placeholder="Title" required>
    <input name="price" value="<?php echo htmlspecialchars($p['price']); ?>" placeholder="Price" required>
    <input name="cat" value="<?php echo htmlspecialchars($p['cat'] ?? ''); ?>" placeholder="Category">
    <textarea name="desc" placeholder="Description"><?php echo htmlspecialchars($p['desc'] ?? ''); ?></textarea>
    <div>Current Image: <?php if (!empty($p['image'])): ?><img src="/<?php echo $p['image']; ?>" style="height:80px;vertical-align:middle;margin-left:8px;"/><?php endif; ?></div>
    <label>Replace Image: <input type="file" name="image" accept="image/*"></label>
    <button class="btn" type="submit">Save Changes</button>
  </form>
</main>
<?php include __DIR__ . '/../footer.php'; ?>
</body>
</html>
