<?php
// Include database connection and session
include 'layouts/session.php';
include 'layouts/dbconn.php';

// Set response headers
header('Content-Type: application/json');

// Initialize response array
$response = array(
    'success' => false,
    'message' => 'An unknown error occurred'
);

// Check if the request is a POST request
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $response['message'] = 'Invalid request method';
    echo json_encode($response);
    exit;
}

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    $response['message'] = 'You must be logged in to perform this action';
    echo json_encode($response);
    exit;
}

// Validate required parameters
if (!isset($_POST['customer_id']) || !isset($_POST['tag_name'])) {
    $response['message'] = 'Missing required parameters';
    echo json_encode($response);
    exit;
}

// Sanitize input
$customerId = intval($_POST['customer_id']);
$tagName = trim($_POST['tag_name']);
$tagColor = isset($_POST['tag_color']) ? trim($_POST['tag_color']) : 'bg-primary';

// Validate customer ID
if ($customerId <= 0) {
    $response['message'] = 'Invalid customer ID';
    echo json_encode($response);
    exit;
}

// Validate tag name
if (empty($tagName)) {
    $response['message'] = 'Tag name cannot be empty';
    echo json_encode($response);
    exit;
}

// Check if customer exists
$checkCustomerQuery = "SELECT customer_id FROM customers WHERE customer_id = ?";
$checkCustomerStmt = $conn->prepare($checkCustomerQuery);
$checkCustomerStmt->bind_param("i", $customerId);
$checkCustomerStmt->execute();
$customerResult = $checkCustomerStmt->get_result();

if ($customerResult->num_rows === 0) {
    $response['message'] = 'Customer not found';
    echo json_encode($response);
    exit;
}

// Create customer_tags table if it doesn't exist
$createTableQuery = "CREATE TABLE IF NOT EXISTS customer_tags (
    tag_id INT AUTO_INCREMENT PRIMARY KEY,
    customer_id INT NOT NULL,
    tag_name VARCHAR(100) NOT NULL,
    tag_color VARCHAR(50) NOT NULL DEFAULT 'bg-primary',
    created_by INT NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (customer_id) REFERENCES customers(customer_id) ON DELETE CASCADE,
    FOREIGN KEY (created_by) REFERENCES users(user_id) ON DELETE CASCADE
)";

if (!$conn->query($createTableQuery)) {
    $response['message'] = 'Error creating tags table: ' . $conn->error;
    echo json_encode($response);
    exit;
}

// Check if tag already exists for this customer
$checkTagQuery = "SELECT tag_id FROM customer_tags WHERE customer_id = ? AND tag_name = ?";
$checkTagStmt = $conn->prepare($checkTagQuery);
$checkTagStmt->bind_param("is", $customerId, $tagName);
$checkTagStmt->execute();
$tagResult = $checkTagStmt->get_result();

if ($tagResult->num_rows > 0) {
    $response['message'] = 'This tag already exists for this customer';
    echo json_encode($response);
    exit;
}

// Insert the new tag
$userId = $_SESSION['user_id'];
$insertTagQuery = "INSERT INTO customer_tags (customer_id, tag_name, tag_color, created_by) VALUES (?, ?, ?, ?)";
$insertTagStmt = $conn->prepare($insertTagQuery);
$insertTagStmt->bind_param("issi", $customerId, $tagName, $tagColor, $userId);

if ($insertTagStmt->execute()) {
    $tagId = $insertTagStmt->insert_id;
    
    // Log the action
    $logDetails = "Added tag '$tagName' to customer ID: $customerId";
    $logQuery = "INSERT INTO admin_logs (user_id, action, details, ip_address) VALUES (?, 'add_tag', ?, ?)";
    $logStmt = $conn->prepare($logQuery);
    $ipAddress = $_SERVER['REMOTE_ADDR'];
    $logStmt->bind_param("iss", $userId, $logDetails, $ipAddress);
    $logStmt->execute();
    
    // Success response
    $response['success'] = true;
    $response['message'] = 'Tag added successfully';
    $response['tag_id'] = $tagId;
    echo json_encode($response);
} else {
    $response['message'] = 'Failed to add tag: ' . $conn->error;
    echo json_encode($response);
}
?>