<?php
// update_product.php (FINAL - with is_featured)

ob_start();
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);

require 'db_connect.php';

header('Content-Type: application/json');
ob_clean();

$response = [];

if (!isset($conn) || $conn->connect_error) {
    http_response_code(500);
    $response['status'] = 'error';
    $response['message'] = 'Database connection failed.';
    echo json_encode($response);
    exit;
}

$id = isset($_POST['id']) ? intval($_POST['id']) : 0;
$name = isset($_POST['name']) ? trim($_POST['name']) : '';
$category = isset($_POST['category']) ? trim($_POST['category']) : '';
$brand_id = isset($_POST['brand_id']) ? intval($_POST['brand_id']) : 0;
$models = isset($_POST['models']) ? trim($_POST['models']) : '';
$description = isset($_POST['description']) ? trim($_POST['description']) : '';
$specification = isset($_POST['specification']) ? trim($_POST['specification']) : '';
$regular_price = isset($_POST['regular_price']) ? floatval($_POST['regular_price']) : 0;
$offer_price = isset($_POST['offer_price']) ? floatval($_POST['offer_price']) : 0;
$image_path = isset($_POST['image_path']) ? trim($_POST['image_path']) : '';
$gallery_images = isset($_POST['gallery_images']) ? trim($_POST['gallery_images']) : '';
// --- NEW: Handle the 'is_featured' flag ---
$is_featured = isset($_POST['is_featured']) ? (int)$_POST['is_featured'] : 0;


if (empty($id) || empty($name) || empty($category) || empty($brand_id)) {
    http_response_code(400);
    $response['status'] = 'error';
    $response['message'] = 'Required fields are missing.';
    echo json_encode($response);
    exit;
}

try {
    // UPDATED: Added 'is_featured' to the UPDATE statement
    $sql = "UPDATE products SET 
                name = ?, 
                category = ?, 
                brand_id = ?, 
                models = ?, 
                description = ?, 
                specification = ?, 
                regular_price = ?, 
                offer_price = ?, 
                image_url = ?, 
                gallery_images = ?,
                is_featured = ?
            WHERE id = ?";

    $stmt = $conn->prepare($sql);
    // UPDATED: Added 'i' for the integer 'is_featured' flag
    $stmt->bind_param("ssisssddssii", 
        $name, 
        $category, 
        $brand_id, 
        $models, 
        $description, 
        $specification, 
        $regular_price, 
        $offer_price, 
        $image_path, 
        $gallery_images, 
        $is_featured, // --- NEW ---
        $id
    );

    if ($stmt->execute()) {
        $response['status'] = 'success';
        $response['message'] = 'Product updated successfully.';
    } else {
        throw new Exception('Failed to execute the update statement.');
    }

    $stmt->close();

} catch (Exception $e) {
    http_response_code(500);
    $response['status'] = 'error';
    $response['message'] = $e->getMessage();
}

echo json_encode($response);
$conn->close();
exit;
?>