<?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['note_text'])) {
    $response['message'] = 'Missing required parameters';
    echo json_encode($response);
    exit;
}

// Sanitize input
$customerId = intval($_POST['customer_id']);
$noteText = trim($_POST['note_text']);

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

// Validate note text
if (empty($noteText)) {
    $response['message'] = 'Note text 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_notes table if it doesn't exist
$createTableQuery = "CREATE TABLE IF NOT EXISTS customer_notes (
    note_id INT AUTO_INCREMENT PRIMARY KEY,
    customer_id INT NOT NULL,
    note_text TEXT NOT NULL,
    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 notes table: ' . $conn->error;
    echo json_encode($response);
    exit;
}

// Insert the new note
$userId = $_SESSION['user_id'];
$insertNoteQuery = "INSERT INTO customer_notes (customer_id, note_text, created_by) VALUES (?, ?, ?)";
$insertNoteStmt = $conn->prepare($insertNoteQuery);
$insertNoteStmt->bind_param("isi", $customerId, $noteText, $userId);

if ($insertNoteStmt->execute()) {
    $noteId = $insertNoteStmt->insert_id;
    
    // Get user information
    $userQuery = "SELECT full_name FROM users WHERE user_id = ?";
    $userStmt = $conn->prepare($userQuery);
    $userStmt->bind_param("i", $userId);
    $userStmt->execute();
    $userResult = $userStmt->get_result();
    $userName = "User";
    
    if ($userResult->num_rows > 0) {
        $userData = $userResult->fetch_assoc();
        $userName = $userData['full_name'];
    }
    
    // Log the action
    $logDetails = "Added note to customer ID: $customerId";
    $logQuery = "INSERT INTO admin_logs (user_id, action, details, ip_address) VALUES (?, 'add_note', ?, ?)";
    $logStmt = $conn->prepare($logQuery);
    $ipAddress = $_SERVER['REMOTE_ADDR'];
    $logStmt->bind_param("iss", $userId, $logDetails, $ipAddress);
    $logStmt->execute();
    
    // Success response
    $response['success'] = true;
    $response['message'] = 'Note added successfully';
    $response['note_id'] = $noteId;
    $response['user_name'] = $userName;
    $response['created_at'] = date('M d, Y');
    echo json_encode($response);
} else {
    $response['message'] = 'Failed to add note: ' . $conn->error;
    echo json_encode($response);
}
?>