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

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

// --- 1. & 2. INCLUDE DATABASE CONNECTION ---
// This uses your existing db_connect.php which 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 {
    // $pdo is initialized in db_connect.php
    $sql = "INSERT INTO brands (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' => 'Brand data saved successfully.']);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Query executed, but no row was inserted. Check constraints.']);
    }

} catch (PDOException $e) {
    // Catches SQL errors like missing tables or incorrect column names
    echo json_encode(['status' => 'error', 'message' => 'Database Error: ' . $e->getMessage()]);
}
?>