<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Void Transaction or Process Refund - 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/sales/void-refund.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/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';
}
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 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('is_ajax_request')) {
    function is_ajax_request() {
        return !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && 
               strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
    }
}

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('has_permission')) {
    function has_permission($permission) {
        return true; // Bypass permission check for now
    }
}

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

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

// Define audit constants if not defined
if (!defined('AUDIT_VOID')) define('AUDIT_VOID', 'void');
if (!defined('AUDIT_REFUND')) define('AUDIT_REFUND', 'refund');
if (!defined('DATETIME_FORMAT')) define('DATETIME_FORMAT', 'Y-m-d H:i:s');

// 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;
    }
}

// Check if it's an AJAX request
if (is_ajax_request()) {
    // 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;
            json_error('Invalid security token');
        }
    }
    
    if ($csrf_valid) {
        // Get action
        $action = $_POST['action'] ?? '';
        
        switch ($action) {
            case 'void':
                process_void();
                break;
            case 'refund':
                process_refund();
                break;
            default:
                json_error('Invalid action');
        }
    }
    exit;
}

// Show form for manual void/refund
show_form();
exit;

/**
 * Process void transaction
 */
function process_void() {
    global $current_user, $user_id;
    
    $sale_id = (int)($_POST['sale_id'] ?? 0);
    $reason = sanitize_input($_POST['void_reason'] ?? '');
    
    if (!$sale_id) {
        json_error('Invalid sale ID');
    }
    
    if (empty($reason)) {
        json_error('Reason is required');
    }
    
    try {
        // Get sale data
        $sale = db_fetch_one("
            SELECT * FROM pos_sales WHERE sale_id = ?
        ", [$sale_id]);
        
        if (!$sale) {
            json_error('Sale not found');
        }
        
        // Check if already voided
        if (($sale['payment_status'] ?? '') == 'voided') {
            json_error('Transaction already voided');
        }
        
        // Begin transaction
        if (function_exists('begin_transaction')) {
            begin_transaction();
        }
        
        $pdo = get_db_connection();
        
        // Update sale record
        $update_sql = "UPDATE pos_sales SET payment_status = 'voided', notes = CONCAT(IFNULL(notes, ''), ?) WHERE sale_id = ?";
        $update_stmt = $pdo->prepare($update_sql);
        $update_stmt->execute([" VOIDED: $reason", $sale_id]);
        
        // Get sale items
        $items_sql = "SELECT * FROM pos_sale_items WHERE sale_id = ?";
        $items_stmt = $pdo->prepare($items_sql);
        $items_stmt->execute([$sale_id]);
        $items = $items_stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Restore stock for each item
        foreach ($items as $item) {
            $product_sql = "SELECT stock_item FROM pos_products WHERE product_id = ?";
            $product_stmt = $pdo->prepare($product_sql);
            $product_stmt->execute([$item['product_id']]);
            $product = $product_stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($product && !empty($product['stock_item'])) {
                // Restore stock
                $stock_sql = "UPDATE pos_products SET current_stock = current_stock + ? WHERE product_id = ?";
                $stock_stmt = $pdo->prepare($stock_sql);
                $stock_stmt->execute([$item['quantity'], $item['product_id']]);
            }
        }
        
        // Audit log
        if (function_exists('audit_log')) {
            audit_log($user_id, 'void', 'pos_sales', $sale_id, 
                     ['status' => 'completed'], 
                     ['status' => 'voided', 'reason' => $reason]);
        }
        
        if (function_exists('commit_transaction')) {
            commit_transaction();
        }
        
        json_success(['sale_id' => $sale_id], 'Transaction voided successfully');
        
    } catch (Exception $e) {
        if (function_exists('rollback_transaction')) {
            rollback_transaction();
        }
        error_log("Void failed: " . $e->getMessage());
        json_error('Failed to void transaction: ' . $e->getMessage());
    }
}

/**
 * Process refund
 */
function process_refund() {
    global $current_user, $user_id;
    
    $sale_id = (int)($_POST['sale_id'] ?? 0);
    $amount = (float)($_POST['refund_amount'] ?? 0);
    $reason = sanitize_input($_POST['refund_reason'] ?? '');
    
    if (!$sale_id) {
        json_error('Invalid sale ID');
    }
    
    if ($amount <= 0) {
        json_error('Invalid refund amount');
    }
    
    if (empty($reason)) {
        json_error('Reason is required');
    }
    
    try {
        // Get sale data
        $sale = db_fetch_one("SELECT * FROM pos_sales WHERE sale_id = ?", [$sale_id]);
        
        if (!$sale) {
            json_error('Sale not found');
        }
        
        if ($amount > $sale['total_amount']) {
            json_error('Refund amount cannot exceed sale total');
        }
        
        // Begin transaction
        if (function_exists('begin_transaction')) {
            begin_transaction();
        }
        
        $pdo = get_db_connection();
        
        // Generate receipt number
        $receipt_number = generate_receipt_number();
        
        // Create refund record
        $refund_sql = "INSERT INTO pos_sales (receipt_number, user_id, outlet_id, customer_name, subtotal, total_amount, payment_method, payment_status, transaction_type, notes, sale_time) 
                       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $refund_stmt = $pdo->prepare($refund_sql);
        $refund_stmt->execute([
            $receipt_number,
            $user_id,
            $sale['outlet_id'],
            $sale['customer_name'] ?? 'Walk-in Customer',
            -$amount,
            -$amount,
            $sale['payment_method'] ?? 'cash',
            'completed',
            'return',
            "Refund for sale {$sale['receipt_number']}: $reason",
            date('Y-m-d H:i:s')
        ]);
        $refund_id = $pdo->lastInsertId();
        
        // Update original sale notes
        $update_sql = "UPDATE pos_sales SET notes = CONCAT(IFNULL(notes, ''), ?) WHERE sale_id = ?";
        $update_stmt = $pdo->prepare($update_sql);
        $update_stmt->execute([" Refund processed: $amount", $sale_id]);
        
        // Audit log
        if (function_exists('audit_log')) {
            audit_log($user_id, 'refund', 'pos_sales', $sale_id, 
                     null, ['amount' => $amount, 'reason' => $reason]);
        }
        
        if (function_exists('commit_transaction')) {
            commit_transaction();
        }
        
        json_success(['refund_id' => $refund_id], 'Refund processed successfully');
        
    } catch (Exception $e) {
        if (function_exists('rollback_transaction')) {
            rollback_transaction();
        }
        error_log("Refund failed: " . $e->getMessage());
        json_error('Failed to process refund: ' . $e->getMessage());
    }
}

/**
 * Show manual void/refund form
 */
function show_form() {
    global $base_path, $current_user;
    
    // Set page title
    $page_title = 'Void / Refund Transaction';
    
    // 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>Void / Refund Transaction</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>
        </head>
        <body>
            <div class="wrapper">
                <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
                    <div class="container-fluid">
                        <a class="navbar-brand" href="#">Void / Refund</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">Void / Refund Transaction</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="pos.php">Terminal</a></li>
                        <li class="breadcrumb-item active">Void/Refund</li>
                    </ol>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Main content -->
    <section class="content">
        <div class="container-fluid">
            <div class="row">
                <div class="col-md-6 offset-md-3">
                    <!-- Search Sale -->
                    <div class="card card-primary">
                        <div class="card-header">
                            <h3 class="card-title">Find Transaction</h3>
                        </div>
                        <div class="card-body">
                            <div class="mb-3">
                                <label for="receipt_search" class="form-label">Receipt Number</label>
                                <input type="text" class="form-control" id="receipt_search" placeholder="Enter receipt number">
                            </div>
                            <button type="button" class="btn btn-primary" onclick="searchReceipt()">
                                <i class="fas fa-search"></i> Search
                            </button>
                        </div>
                    </div>
                    
                    <!-- Transaction Details (hidden initially) -->
                    <div id="transactionDetails" style="display: none;">
                        <div class="card card-info mt-3">
                            <div class="card-header">
                                <h3 class="card-title">Transaction Details</h3>
                            </div>
                            <div class="card-body" id="transactionInfo"></div>
                        </div>
                        
                        <!-- Void Form -->
                        <div class="card card-danger mt-3" id="voidForm" style="display: none;">
                            <div class="card-header">
                                <h3 class="card-title">Void Transaction</h3>
                            </div>
                            <form id="voidFormSubmit">
                                <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                                <input type="hidden" name="action" value="void">
                                <input type="hidden" name="sale_id" id="void_sale_id">
                                
                                <div class="card-body">
                                    <div class="mb-3">
                                        <label for="void_reason" class="form-label">Reason for voiding</label>
                                        <textarea class="form-control" id="void_reason" name="void_reason" rows="3" required></textarea>
                                    </div>
                                    
                                    <div class="alert alert-warning">
                                        <i class="fas fa-exclamation-triangle me-2"></i>
                                        Voiding will reverse the transaction and restore inventory. This cannot be undone.
                                    </div>
                                </div>
                                
                                <div class="card-footer">
                                    <button type="submit" class="btn btn-danger">Void Transaction</button>
                                </div>
                            </form>
                        </div>
                        
                        <!-- Refund Form -->
                        <div class="card card-warning mt-3" id="refundForm" style="display: none;">
                            <div class="card-header">
                                <h3 class="card-title">Process Refund</h3>
                            </div>
                            <form id="refundFormSubmit">
                                <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                                <input type="hidden" name="action" value="refund">
                                <input type="hidden" name="sale_id" id="refund_sale_id">
                                
                                <div class="card-body">
                                    <div class="mb-3">
                                        <label for="refund_amount" class="form-label">Refund Amount</label>
                                        <div class="input-group">
                                            <span class="input-group-text"><?php echo defined('CURRENCY_SYMBOL') ? CURRENCY_SYMBOL : 'RWF'; ?></span>
                                            <input type="number" class="form-control" id="refund_amount" name="refund_amount" 
                                                   step="0.01" min="0.01" required>
                                        </div>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label for="refund_reason" class="form-label">Reason for refund</label>
                                        <textarea class="form-control" id="refund_reason" name="refund_reason" rows="3" required></textarea>
                                    </div>
                                </div>
                                
                                <div class="card-footer">
                                    <button type="submit" class="btn btn-warning">Process Refund</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
    
    <script>
    function searchReceipt() {
        const receipt = $('#receipt_search').val();
        if (!receipt) {
            alert('Please enter a receipt number');
            return;
        }
        
        $.ajax({
            url: '/HMSPOS/api/get-sale.php',
            method: 'GET',
            data: { receipt: receipt },
            dataType: 'json',
            success: function(response) {
                if (response.status === 'success') {
                    displayTransaction(response.data);
                } else {
                    alert('Transaction not found');
                }
            },
            error: function(xhr, status, error) {
                console.error('Search error:', error);
                alert('Failed to search transaction');
            }
        });
    }
    
    function displayTransaction(sale) {
        $('#transactionDetails').show();
        
        let html = `
            <table class="table table-sm">
                <tr>
                    <th>Receipt Number:</th>
                    <td>${sale.receipt_number || ''}</td>
                </tr>
                <tr>
                    <th>Date:</th>
                    <td>${sale.sale_time || ''}</td>
                </tr>
                <tr>
                    <th>Cashier:</th>
                    <td>${sale.cashier || ''}</td>
                </tr>
                <tr>
                    <th>Customer:</th>
                    <td>${sale.customer_name || 'Walk-in'}</td>
                </tr>
                <tr>
                    <th>Total Amount:</th>
                    <td><strong>${formatCurrency(sale.total_amount || 0)}</strong></td>
                </tr>
                <tr>
                    <th>Payment Method:</th>
                    <td>${sale.payment_method || 'Cash'}</td>
                </tr>
                <tr>
                    <th>Status:</th>
                    <td><span class="badge bg-${sale.payment_status === 'completed' ? 'success' : 'danger'}">${sale.payment_status || 'unknown'}</span></td>
                </tr>
            </table>
        `;
        
        $('#transactionInfo').html(html);
        
        if (sale.payment_status === 'completed') {
            $('#voidForm').show();
            $('#refundForm').show();
            $('#void_sale_id').val(sale.sale_id);
            $('#refund_sale_id').val(sale.sale_id);
            
            // Set max refund amount
            $('#refund_amount').attr('max', sale.total_amount);
        } else {
            $('#voidForm').hide();
            $('#refundForm').hide();
        }
    }
    
    function formatCurrency(amount) {
        return 'RWF ' + parseFloat(amount).toLocaleString();
    }
    
    $('#voidFormSubmit').on('submit', function(e) {
        e.preventDefault();
        
        if (confirm('Are you sure you want to void this transaction?')) {
            $.ajax({
                url: 'void-refund.php',
                method: 'POST',
                data: $(this).serialize(),
                dataType: 'json',
                success: function(response) {
                    if (response.status === 'success') {
                        alert('Transaction voided successfully');
                        location.reload();
                    } else {
                        alert('Failed to void transaction: ' + response.message);
                    }
                },
                error: function(xhr, status, error) {
                    alert('Failed to void transaction: ' + error);
                }
            });
        }
    });
    
    $('#refundFormSubmit').on('submit', function(e) {
        e.preventDefault();
        
        if (confirm('Process this refund?')) {
            $.ajax({
                url: 'void-refund.php',
                method: 'POST',
                data: $(this).serialize(),
                dataType: 'json',
                success: function(response) {
                    if (response.status === 'success') {
                        alert('Refund processed successfully');
                        location.reload();
                    } else {
                        alert('Failed to process refund: ' + response.message);
                    }
                },
                error: function(xhr, status, error) {
                    alert('Failed to process refund: ' + error);
                }
            });
        }
    });
    </script>
    
    <style>
    .me-1 { margin-right: 0.25rem; }
    .me-2 { margin-right: 0.5rem; }
    .mb-3 { margin-bottom: 1rem; }
    .mt-3 { margin-top: 1rem; }
    .badge.bg-success { background-color: #28a745; color: #fff; }
    .badge.bg-danger { background-color: #dc3545; color: #fff; }
    .badge.bg-warning { background-color: #ffc107; color: #000; }
    </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>';
    }
}
?>