<?php
// FINAL add_category.php using centralized connection

ini_set('display_errors', 1);
error_reporting(E_ALL);
header('Content-Type: application/json');

// --- 1. & 2. INCLUDE DATABASE CONNECTION ---
// This file now provides the $pdo object
require_once 'db_connect.php'; 

// --- 3. GET DATA FROM APP ---
if (!isset($_POST['name']) || !isset($_POST['image_path'])) {
    die(json_encode(['status' => 'error', 'message' => 'Required fields (name, image_path) are missing.']));
}

$name = $_POST['name'];
$image_path = $_POST['image_path'];

// --- 4. INSERT INTO DATABASE ---
try {
    // We use $pdo here as it was defined in your db_connect.php
    $sql = "INSERT INTO categories (name, image_url) VALUES (?, ?)";
    $stmt = $pdo->prepare($sql);
    
    // Execute the statement
    $stmt->execute([$name, $image_path]);

    // **CRITICAL CHECK**: Was a row actually inserted?
    if ($stmt->rowCount() > 0) {
        echo json_encode(['status' => 'success', 'message' => 'Category data saved successfully.']);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Query executed, but no row was inserted. Check constraints.']);
    }

} catch (PDOException $e) {
    // This will catch any SQL errors (like "table not found" or "column name wrong").
    echo json_encode(['status' => 'error', 'message' => 'Database Error: ' . $e->getMessage()]);
}
?>