<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * POS Checkout Processor - ULTIMATE 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
$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/sales/ -> /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';
}

// Require authentication
require_auth();

// Define helper functions if they don't exist
if (!function_exists('json_success')) {
    function json_success($data = null, $message = 'Success') {
        header('Content-Type: application/json');
        echo json_encode([
            'status' => 'success',
            'message' => $message,
            'data' => $data
        ]);
        exit;
    }
}

if (!function_exists('json_error')) {
    function json_error($message = 'Error', $errors = null, $status_code = 400) {
        http_response_code($status_code);
        header('Content-Type: application/json');
        $response = [
            'status' => 'error',
            'message' => $message
        ];
        if ($errors !== null) {
            $response['errors'] = $errors;
        }
        echo json_encode($response);
        exit;
    }
}

if (!function_exists('generate_receipt_number')) {
    function generate_receipt_number() {
        return 'RCP-' . date('Ymd') . '-' . str_pad(rand(1, 999), 3, '0', STR_PAD_LEFT);
    }
}

// Check if it's a POST request
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    json_error('Invalid request method');
}

// Get action
$action = $_POST['action'] ?? '';

if ($action !== 'process') {
    json_error('Invalid action');
}

// Get checkout data
$data = json_decode($_POST['data'] ?? '[]', true);

if (empty($data)) {
    json_error('No checkout data received');
}

// Validate required fields
if (empty($data['outlet_id'])) {
    json_error('Outlet ID is required');
}

if (empty($data['items']) || !is_array($data['items'])) {
    json_error('No items in cart');
}

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

if (!$user_id) {
    json_error('User not authenticated');
}

// Check for open shift
try {
    $active_shift = db_fetch_one("
        SELECT shift_id FROM pos_shifts 
        WHERE user_id = ? AND status = 'open'
        ORDER BY opened_at DESC LIMIT 1
    ", [$user_id]);
    
    if (!$active_shift) {
        json_error('No open shift found. Please open a shift first.');
    }
    
    $shift_id = $active_shift['shift_id'];
} catch (Exception $e) {
    error_log("Error checking shift: " . $e->getMessage());
    json_error('Failed to verify shift status');
}

// Begin transaction
try {
    if (function_exists('begin_transaction')) {
        begin_transaction();
    }
    
    // Calculate totals
    $subtotal = $data['subtotal'] ?? 0;
    $discount = $data['discount'] ?? 0;
    $discount_type = $data['discount_type'] ?? 'fixed';
    
    // Calculate discount amount
    $discount_amount = $discount;
    if ($discount_type === 'percentage') {
        $discount_amount = ($subtotal * $discount) / 100;
    }
    
    $tax = $subtotal * 0.18; // 18% VAT
    $total = $subtotal + $tax - $discount_amount;
    
    // Generate receipt number
    $receipt_number = generate_receipt_number();
    
    // Get table columns to determine what to insert
    $pdo = get_db_connection();
    
    try {
        $columns = $pdo->query("SHOW COLUMNS FROM pos_sales")->fetchAll(PDO::FETCH_COLUMN);
    } catch (Exception $e) {
        // If table doesn't exist, create it
        $create_sql = "
            CREATE TABLE IF NOT EXISTS pos_sales (
                sale_id INT PRIMARY KEY AUTO_INCREMENT,
                receipt_number VARCHAR(50) UNIQUE,
                shift_id INT,
                user_id INT,
                outlet_id INT,
                customer_name VARCHAR(255) DEFAULT 'Walk-in Customer',
                guest_id INT,
                subtotal DECIMAL(10,2) DEFAULT 0,
                discount DECIMAL(10,2) DEFAULT 0,
                tax DECIMAL(10,2) DEFAULT 0,
                total_amount DECIMAL(10,2) DEFAULT 0,
                payment_method VARCHAR(50) DEFAULT 'cash',
                payment_status VARCHAR(50) DEFAULT 'completed',
                sale_time DATETIME,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )
        ";
        $pdo->exec($create_sql);
        $columns = $pdo->query("SHOW COLUMNS FROM pos_sales")->fetchAll(PDO::FETCH_COLUMN);
    }
    
    // Build the insert query dynamically
    $insert_fields = [];
    $insert_values = [];
    $placeholders = [];
    
    // Always include these core fields
    $core_fields = [
        'receipt_number' => $receipt_number,
        'user_id' => $user_id,
        'outlet_id' => $data['outlet_id'],
        'subtotal' => $subtotal,
        'total_amount' => $total,
        'sale_time' => date('Y-m-d H:i:s')
    ];
    
    foreach ($core_fields as $field => $value) {
        if (in_array($field, $columns)) {
            $insert_fields[] = $field;
            $insert_values[] = $value;
            $placeholders[] = '?';
        }
    }
    
    // Add optional fields if they exist in the table
    $optional_fields = [
        'shift_id' => $shift_id,
        'discount' => $discount_amount,
        'tax' => $tax,
        'customer_name' => $data['customer_name'] ?? 'Walk-in Customer',
        'guest_id' => $data['guest_id'] ?? null,
        'payment_method' => $data['payment_method'] ?? 'cash',
        'payment_status' => 'completed'
    ];
    
    foreach ($optional_fields as $field => $value) {
        if (in_array($field, $columns)) {
            $insert_fields[] = $field;
            $insert_values[] = $value;
            $placeholders[] = '?';
        }
    }
    
    // If no fields to insert, something is wrong
    if (empty($insert_fields)) {
        throw new Exception("No valid columns found in pos_sales table");
    }
    
    // Build and execute the insert query
    $sql = "INSERT INTO pos_sales (" . implode(', ', $insert_fields) . ") 
            VALUES (" . implode(', ', $placeholders) . ")";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute($insert_values);
    
    $sale_id = $pdo->lastInsertId();
    
    // Insert sale items
    foreach ($data['items'] as $item) {
        // Check if pos_sale_items table exists
        try {
            $item_columns = $pdo->query("SHOW COLUMNS FROM pos_sale_items")->fetchAll(PDO::FETCH_COLUMN);
        } catch (Exception $e) {
            // Create the items table if it doesn't exist
            $create_items_sql = "
                CREATE TABLE IF NOT EXISTS pos_sale_items (
                    sale_item_id INT PRIMARY KEY AUTO_INCREMENT,
                    sale_id INT NOT NULL,
                    product_id INT NOT NULL,
                    quantity INT NOT NULL DEFAULT 1,
                    unit_price DECIMAL(10,2) NOT NULL,
                    total_amount DECIMAL(10,2) NOT NULL,
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    FOREIGN KEY (sale_id) REFERENCES pos_sales(sale_id) ON DELETE CASCADE
                )
            ";
            $pdo->exec($create_items_sql);
            $item_columns = $pdo->query("SHOW COLUMNS FROM pos_sale_items")->fetchAll(PDO::FETCH_COLUMN);
        }
        
        $item_fields = ['sale_id', 'product_id', 'quantity', 'unit_price', 'total_amount'];
        $item_values = [
            $sale_id,
            $item['id'],
            $item['quantity'],
            $item['price'],
            $item['price'] * $item['quantity']
        ];
        
        // Filter fields that actually exist in the table
        $filtered_fields = [];
        $filtered_values = [];
        $item_placeholders = [];
        
        foreach ($item_fields as $i => $field) {
            if (in_array($field, $item_columns)) {
                $filtered_fields[] = $field;
                $filtered_values[] = $item_values[$i];
                $item_placeholders[] = '?';
            }
        }
        
        if (!empty($filtered_fields)) {
            $item_sql = "INSERT INTO pos_sale_items (" . implode(', ', $filtered_fields) . ") 
                         VALUES (" . implode(', ', $item_placeholders) . ")";
            $item_stmt = $pdo->prepare($item_sql);
            $item_stmt->execute($filtered_values);
        }
        
        // Update stock if item is stock-controlled
        try {
            $product = db_fetch_one("SELECT stock_item, current_stock FROM pos_products WHERE product_id = ?", [$item['id']]);
            if ($product && !empty($product['stock_item'])) {
                $new_stock = max(0, ($product['current_stock'] ?? 0) - $item['quantity']);
                $update_sql = "UPDATE pos_products SET current_stock = ? WHERE product_id = ?";
                $update_stmt = $pdo->prepare($update_sql);
                $update_stmt->execute([$new_stock, $item['id']]);
            }
        } catch (Exception $e) {
            error_log("Error updating stock for product {$item['id']}: " . $e->getMessage());
        }
    }
    
    // Commit transaction
    if (function_exists('commit_transaction')) {
        commit_transaction();
    }
    
    // Return success response
    json_success(['sale_id' => $sale_id, 'receipt_number' => $receipt_number], 'Checkout successful');
    
} catch (Exception $e) {
    if (function_exists('rollback_transaction')) {
        rollback_transaction();
    }
    error_log("Checkout error: " . $e->getMessage());
    json_error('Checkout failed: ' . $e->getMessage());
}
?>