<?php
require_once __DIR__ . '/../../app/includes/auth.php';
require_once __DIR__ . '/../../app/includes/product_helpers.php';
require_auth(); require_role_access('*'); verify_csrf();

$id = (int)($_GET['id'] ?? 0);
$stmt = db()->prepare('SELECT * FROM products WHERE id = ?');
$stmt->execute([$id]);
$product = $stmt->fetch();
if (!$product) {
    flash('error', 'Product not found.');
    redirect('/products/index.php');
}

if ((string)post('action') === 'toggle_status') {
    $newStatus = $product['status'] === 'active' ? 'inactive' : 'active';
    $stmt = db()->prepare('UPDATE products SET status = ?, updated_at = ? WHERE id = ?');
    $stmt->execute([$newStatus, now(), $id]);
    log_activity('product_status_changed', 'Changed product status to ' . $newStatus . ' for ' . $product['product_name'] . '.');
    flash('success', 'Product status updated successfully.');
    redirect('/products/index.php');
}

[$data, $errors] = validate_product_input($_POST);
if ($errors) {
    flash('error', implode(' ', $errors));
    redirect('/products/edit.php?id=' . $id);
}
if (duplicate_product_exists($data, $id)) {
    flash('error', 'A product with the same name, brand, and model already exists.');
    redirect('/products/edit.php?id=' . $id);
}

$stmt = db()->prepare('UPDATE products SET product_category=?, product_name=?, description=?, brand=?, model=?, unit=?, unit_price=?, status=?, updated_at=? WHERE id=?');
$stmt->execute([$data['product_category'], $data['product_name'], $data['description'], $data['brand'], $data['model'], $data['unit'], $data['unit_price'], $data['status'], now(), $id]);
log_activity('product_updated', 'Updated product ' . $data['product_name'] . '.');
flash('success', 'Product updated successfully.');
redirect('/products/index.php');
