<?php
session_start();
header('Content-Type: application/json');
require_once '../config/db.php';

// Only admin can use
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    exit;
}

// Table/column mapping (must match update_table.php)
$tables = [
    'suppliers'   => ['table' => 'suppliers',   'column' => 'name'],
    'formats'     => ['table' => 'formats',     'column' => 'name'],
    'market'      => ['table' => 'markets',     'column' => 'name'],
    'unilever'    => ['table' => 'unilever',    'column' => 'name'],
    'competitors' => ['table' => 'competitors', 'column' => 'name'],
    'planning'    => ['table' => 'planning',    'column' => 'name'],
];

// Validate input
$action = $_POST['action'] ?? '';
$table_key = $_POST['table'] ?? '';
$value = trim($_POST['value'] ?? '');
$id = intval($_POST['id'] ?? 0);

if (!isset($tables[$table_key])) {
    echo json_encode(['success' => false, 'error' => 'Invalid table']);
    exit;
}
$table = $tables[$table_key]['table'];
$column = $tables[$table_key]['column'];

if ($action === 'add') {
    if ($value === '') {
        echo json_encode(['success' => false, 'error' => 'Value required']);
        exit;
    }
    // Prevent duplicates
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM $table WHERE $column = ?");
    $stmt->execute([$value]);
    $count = $stmt->fetchColumn();
    if ($count > 0) {
        echo json_encode(['success' => false, 'error' => 'Value already exists']);
        exit;
    }
    // Insert new value (for planning, only name and created_by)
    if ($table === 'planning') {
        $created_by = $_SESSION['user_id'] ?? null;
        if (!$created_by) {
            echo json_encode(['success' => false, 'error' => 'User ID required']);
            exit;
        }
        $stmt = $pdo->prepare("INSERT INTO planning (name, created_by) VALUES (?, ?)");
        if ($stmt->execute([$value, $created_by])) {
            $new_id = $pdo->lastInsertId();
            echo json_encode(['success' => true, 'id' => $new_id]);
        } else {
            echo json_encode(['success' => false, 'error' => 'Insert failed']);
        }
        exit;
    } else {
        $stmt = $pdo->prepare("INSERT INTO $table ($column) VALUES (?)");
        if ($stmt->execute([$value])) {
            $new_id = $pdo->lastInsertId();
            echo json_encode(['success' => true, 'id' => $new_id]);
        } else {
            echo json_encode(['success' => false, 'error' => 'Insert failed']);
        }
        exit;
    }
}

if ($action === 'update') {
    if ($id <= 0 || $value === '') {
        echo json_encode(['success' => false, 'error' => 'ID and value required']);
        exit;
    }
    // Prevent duplicates
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM $table WHERE $column = ? AND id != ?");
    $stmt->execute([$value, $id]);
    $count = $stmt->fetchColumn();
    if ($count > 0) {
        echo json_encode(['success' => false, 'error' => 'Value already exists']);
        exit;
    }
    // Update value (for planning, only name)
    if ($table === 'planning') {
        $stmt = $pdo->prepare("UPDATE planning SET name = ? WHERE id = ?");
        if ($stmt->execute([$value, $id])) {
            echo json_encode(['success' => true]);
        } else {
            echo json_encode(['success' => false, 'error' => 'Update failed']);
        }
        exit;
    } else {
        $stmt = $pdo->prepare("UPDATE $table SET $column = ? WHERE id = ?");
        if ($stmt->execute([$value, $id])) {
            echo json_encode(['success' => true]);
        } else {
            echo json_encode(['success' => false, 'error' => 'Update failed']);
        }
        exit;
    }
}

if ($action === 'delete') {
    if ($id <= 0) {
        echo json_encode(['success' => false, 'error' => 'ID required']);
        exit;
    }
    $stmt = $pdo->prepare("DELETE FROM $table WHERE id = ?");
    if ($stmt->execute([$id])) {
        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['success' => false, 'error' => 'Delete failed']);
    }
    exit;
}

echo json_encode(['success' => false, 'error' => 'Invalid action']);