<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Process Refund - FIXED PATH
 * 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 from admin/billing/payments/
$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/admin/billing/payments/ -> /HMSPOS/
    $base_path = dirname(__DIR__, 4);
}

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

// Method 4: Try to find by traversing up until we find config directory
$current_dir = __DIR__;
while (!file_exists($current_dir . '/config/config.php') && $current_dir != dirname($current_dir)) {
    $current_dir = dirname($current_dir);
}
if (file_exists($current_dir . '/config/config.php')) {
    $base_path = $current_dir;
}

// Load required files
$required_files = [
    '/config/config.php',
    '/config/constants.php',
    '/config/database.php',
    '/config/helpers.php',
    '/config/auth.php',
    '/config/csrf.php'
];

foreach ($required_files as $file) {
    $file_path = $base_path . $file;
    if (file_exists($file_path)) {
        require_once $file_path;
    } else {
        error_log("Required file not found: " . $file_path);
        // Try alternate path without HMSPOS
        $alt_path = str_replace('/HMSPOS', '', $base_path) . $file;
        if (file_exists($alt_path)) {
            require_once $alt_path;
        } else {
            // Try one more fallback
            $fallback_path = dirname(__DIR__, 2) . $file;
            if (file_exists($fallback_path)) {
                require_once $fallback_path;
            }
        }
    }
}

// Require authentication
if (function_exists('require_auth')) {
    require_auth();
} else {
    // Fallback authentication check
    session_start();
    if (!isset($_SESSION['user_id'])) {
        header('Location: /HMSPOS/public/login.php');
        exit;
    }
}

// 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 escape_html function if it doesn't exist
if (!function_exists('escape_html')) {
    function escape_html($text) {
        return htmlspecialchars($text ?? '', ENT_QUOTES, 'UTF-8');
    }
}

// Define sanitize_input function if it doesn't exist
if (!function_exists('sanitize_input')) {
    function sanitize_input($data) {
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
        return $data;
    }
}

// Define format_datetime function if it doesn't exist
if (!function_exists('format_datetime')) {
    function format_datetime($datetime, $format = 'M d, Y H:i') {
        if (empty($datetime)) return '';
        return date($format, strtotime($datetime));
    }
}

// Define format_currency function if it doesn't exist
if (!function_exists('format_currency')) {
    function format_currency($amount) {
        return 'RWF ' . number_format($amount ?? 0, 2);
    }
}

// Define set_flash_message function if it doesn't exist
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];
    }
}

// Define redirect function if it doesn't exist
if (!function_exists('redirect')) {
    function redirect($url) {
        header('Location: ' . $url);
        exit;
    }
}

// Define base_url function if it doesn't exist
if (!function_exists('base_url')) {
    function base_url($path = '') {
        return '/HMSPOS/' . ltrim($path, '/');
    }
}

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

// Define verify_csrf_token function if it doesn't exist
if (!function_exists('verify_csrf_token')) {
    function verify_csrf_token($token) {
        return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
    }
}

// Define begin_transaction function if it doesn't exist
if (!function_exists('begin_transaction')) {
    function begin_transaction() {
        if (function_exists('db_connect')) {
            $db = db_connect();
            if ($db) {
                $db->beginTransaction();
            }
        }
    }
}

// Define commit_transaction function if it doesn't exist
if (!function_exists('commit_transaction')) {
    function commit_transaction() {
        if (function_exists('db_connect')) {
            $db = db_connect();
            if ($db && $db->inTransaction()) {
                $db->commit();
            }
        }
    }
}

// Define rollback_transaction function if it doesn't exist
if (!function_exists('rollback_transaction')) {
    function rollback_transaction() {
        if (function_exists('db_connect')) {
            $db = db_connect();
            if ($db && $db->inTransaction()) {
                $db->rollBack();
            }
        }
    }
}

// Define audit_log function if it doesn't exist
if (!function_exists('audit_log')) {
    function audit_log($user_id, $action, $table, $record_id, $old_values = null, $new_values = null) {
        // Simplified audit log - just log to error log
        error_log("AUDIT: User $user_id - $action on $table:$record_id");
    }
}

// Define log_message function if it doesn't exist
if (!function_exists('log_message')) {
    function log_message($message, $level = 'INFO') {
        error_log("[$level] $message");
    }
}

// Define constants if not defined
if (!defined('CSRF_TOKEN_NAME')) {
    define('CSRF_TOKEN_NAME', 'csrf_token');
}
if (!defined('AUDIT_REFUND')) {
    define('AUDIT_REFUND', 'refund');
}
if (!defined('CURRENCY_SYMBOL')) {
    define('CURRENCY_SYMBOL', 'RWF');
}

// Check permission
if (function_exists('require_permission')) {
    require_permission('billing.refunds');
}

// Set page title
$page_title = 'Process Refund';

// Get current user
$current_user = null;
if (function_exists('current_user')) {
    $current_user = current_user();
} else {
    // Fallback: get user from session
    if (isset($_SESSION['user_id'])) {
        try {
            if (function_exists('db_fetch_one')) {
                $current_user = db_fetch_one("SELECT * FROM users WHERE user_id = ?", [$_SESSION['user_id']]);
            }
        } catch (Exception $e) {
            error_log("Error fetching current user: " . $e->getMessage());
        }
    }
}

$user_id = $current_user['user_id'] ?? $_SESSION['user_id'] ?? 0;

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

// Get payment ID from URL
$payment_id = isset($_GET['payment_id']) ? (int)$_GET['payment_id'] : 0;

if (!$payment_id) {
    if (function_exists('set_flash_message')) {
        set_flash_message('danger', 'Invalid payment ID');
    }
    if (function_exists('redirect')) {
        redirect('index.php');
    } else {
        header('Location: index.php');
        exit;
    }
}

// Get payment data
$payment = [];
if (function_exists('db_fetch_one')) {
    try {
        $payment = db_fetch_one("
            SELECT p.*, g.first_name, g.last_name, g.email,
                   pm.method_name,
                   i.invoice_number, i.total_amount, i.paid_amount
            FROM payments p
            JOIN guests g ON p.guest_id = g.guest_id
            JOIN payment_methods pm ON p.payment_method_id = pm.payment_method_id
            LEFT JOIN invoices i ON p.invoice_id = i.invoice_id
            WHERE p.payment_id = ?
        ", [$payment_id]) ?: [];
    } catch (Exception $e) {
        error_log("Error fetching payment: " . $e->getMessage());
    }
}

if (empty($payment)) {
    if (function_exists('set_flash_message')) {
        set_flash_message('danger', 'Payment not found');
    }
    if (function_exists('redirect')) {
        redirect('index.php');
    } else {
        header('Location: index.php');
        exit;
    }
}

// Check if payment can be refunded
if (($payment['status'] ?? '') != 'completed') {
    if (function_exists('set_flash_message')) {
        set_flash_message('danger', 'Only completed payments can be refunded');
    }
    if (function_exists('redirect')) {
        redirect('index.php');
    } else {
        header('Location: index.php');
        exit;
    }
}

// Get refund methods (usually same as payment methods)
$refund_methods = [];
if (function_exists('db_fetch_all')) {
    try {
        $refund_methods = db_fetch_all("SELECT * FROM payment_methods WHERE is_active = 1 ORDER BY sort_order") ?: [];
    } catch (Exception $e) {
        error_log("Error fetching refund methods: " . $e->getMessage());
    }
}

// Handle form submission
$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $token = $_POST['csrf_token'] ?? '';
    if (function_exists('verify_csrf_token') && !verify_csrf_token($token)) {
        $errors[] = 'Invalid security token. Please try again.';
    } else {
        $refund_amount = isset($_POST['refund_amount']) ? (float)$_POST['refund_amount'] : 0;
        $refund_method_id = isset($_POST['refund_method_id']) ? (int)$_POST['refund_method_id'] : 0;
        $reason = isset($_POST['reason']) ? sanitize_input($_POST['reason']) : '';
        $other_reason = isset($_POST['other_reason']) ? sanitize_input($_POST['other_reason']) : '';
        $notes = isset($_POST['notes']) ? sanitize_input($_POST['notes']) : '';
        
        // If reason is "Other", use the custom reason
        if ($reason === 'Other' && !empty($other_reason)) {
            $reason = $other_reason;
        }
        
        // Validate
        if ($refund_amount <= 0) {
            $errors[] = 'Refund amount must be greater than 0';
        }
        
        if ($refund_amount > ($payment['amount'] ?? 0)) {
            $errors[] = 'Refund amount cannot exceed payment amount';
        }
        
        if (!$refund_method_id) {
            $errors[] = 'Please select a refund method';
        }
        
        if (empty($reason)) {
            $errors[] = 'Please provide a reason for the refund';
        }
        
        if (empty($errors)) {
            try {
                if (function_exists('begin_transaction')) {
                    begin_transaction();
                }
                
                // Generate refund payment number
                $refund_number = 'REF-' . date('Ymd') . '-' . str_pad(rand(1, 999), 3, '0', STR_PAD_LEFT);
                
                // Create refund record (negative payment)
                $refund_id = null;
                if (function_exists('db_insert')) {
                    $refund_id = db_insert('payments', [
                        'payment_number' => $refund_number,
                        'invoice_id' => $payment['invoice_id'] ?? null,
                        'guest_id' => $payment['guest_id'] ?? 0,
                        'payment_method_id' => $refund_method_id,
                        'amount' => -$refund_amount,
                        'payment_date' => date('Y-m-d H:i:s'),
                        'reference_number' => $payment['payment_number'] ?? '',
                        'notes' => "Refund for payment {$payment['payment_number']}: $reason" . ($notes ? " - $notes" : ""),
                        'received_by' => $user_id,
                        'status' => 'completed',
                        'created_at' => date('Y-m-d H:i:s')
                    ]);
                }
                
                // Update original payment status
                $new_payment_status = ($refund_amount >= ($payment['amount'] ?? 0)) ? 'refunded' : 'partial_refund';
                if (function_exists('db_update')) {
                    db_update('payments', [
                        'status' => $new_payment_status,
                        'notes' => (($payment['notes'] ?? '') ? $payment['notes'] . ' ' : '') . "Partial refund of $refund_amount processed"
                    ], 'payment_id = ?', [$payment_id]);
                }
                
                // Update invoice if linked
                if (!empty($payment['invoice_id']) && function_exists('db_fetch_one') && function_exists('db_update')) {
                    $invoice = db_fetch_one("SELECT * FROM invoices WHERE invoice_id = ?", [$payment['invoice_id']]);
                    if ($invoice) {
                        $new_paid = ($invoice['paid_amount'] ?? 0) - $refund_amount;
                        $new_status = $new_paid <= 0 ? 'sent' : ($new_paid < ($invoice['total_amount'] ?? 0) ? 'partial' : 'paid');
                        
                        db_update('invoices', [
                            'paid_amount' => $new_paid,
                            // 'balance' field removed - this is a generated column in the database
                            'status' => $new_status
                        ], 'invoice_id = ?', [$payment['invoice_id']]);
                    }
                }
                
                // Create guest activity
                if (function_exists('db_insert')) {
                    db_insert('guest_activity', [
                        'guest_id' => $payment['guest_id'] ?? 0,
                        'activity_type' => 'refund',
                        'description' => "Refund of " . format_currency($refund_amount) . " processed for payment {$payment['payment_number']}. Reason: $reason",
                        'reference_id' => $refund_id,
                        'reference_type' => 'payment',
                        'created_by' => $user_id,
                        'created_at' => date('Y-m-d H:i:s')
                    ]);
                }
                
                // Audit log
                if (function_exists('audit_log')) {
                    audit_log($user_id, AUDIT_REFUND, 'payments', $payment_id, 
                             ['amount' => $payment['amount'] ?? 0], 
                             ['refund_amount' => $refund_amount, 'reason' => $reason]);
                }
                
                if (function_exists('commit_transaction')) {
                    commit_transaction();
                }
                
                if (function_exists('set_flash_message')) {
                    set_flash_message('success', 'Refund processed successfully');
                }
                
                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 process refund: ' . $e->getMessage();
                if (function_exists('log_message')) {
                    log_message("Refund failed: " . $e->getMessage(), 'ERROR');
                }
            }
        }
    }
}

// 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>Process Refund</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; }
            .me-1 { margin-right: 0.25rem; }
            .me-2 { margin-right: 0.5rem; }
            .ms-2 { margin-left: 0.5rem; }
            .mb-2 { margin-bottom: 0.5rem; }
            .mb-3 { margin-bottom: 1rem; }
            .mt-2 { margin-top: 0.5rem; }
        </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="#">Process 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">Process Refund</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/billing/dashboard.php">Billing</a></li>
                    <li class="breadcrumb-item"><a href="index.php">Payments</a></li>
                    <li class="breadcrumb-item active">Refund</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- 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; ?>

        <div class="row">
            <div class="col-md-8 offset-md-2">
                <!-- Payment Summary -->
                <div class="card card-info">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-info-circle me-1"></i>
                            Original Payment Details
                        </h3>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-4">
                                <strong>Payment #:</strong><br>
                                <?php echo htmlspecialchars($payment['payment_number'] ?? 'N/A'); ?>
                            </div>
                            <div class="col-md-4">
                                <strong>Guest:</strong><br>
                                <?php echo escape_html(($payment['first_name'] ?? '') . ' ' . ($payment['last_name'] ?? '')); ?>
                            </div>
                            <div class="col-md-4">
                                <strong>Date:</strong><br>
                                <?php echo isset($payment['payment_date']) ? date('M d, Y H:i', strtotime($payment['payment_date'])) : 'N/A'; ?>
                            </div>
                        </div>
                        <div class="row mt-2">
                            <div class="col-md-4">
                                <strong>Method:</strong><br>
                                <?php echo htmlspecialchars($payment['method_name'] ?? 'N/A'); ?>
                            </div>
                            <div class="col-md-4">
                                <strong>Amount:</strong><br>
                                <span class="text-success"><?php echo format_currency($payment['amount'] ?? 0); ?></span>
                            </div>
                            <div class="col-md-4">
                                <strong>Invoice:</strong><br>
                                <?php echo htmlspecialchars($payment['invoice_number'] ?? 'N/A'); ?>
                            </div>
                        </div>
                        <?php if (!empty($payment['reference_number'])): ?>
                        <div class="row mt-2">
                            <div class="col-12">
                                <strong>Reference:</strong><br>
                                <?php echo htmlspecialchars($payment['reference_number']); ?>
                            </div>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Refund Form -->
                <div class="card card-warning">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-undo-alt me-1"></i>
                            Refund Details
                        </h3>
                    </div>
                    
                    <form method="POST" id="refundForm">
                        <?php if (function_exists('csrf_field')): ?>
                            <?php echo csrf_field(); ?>
                        <?php else: ?>
                            <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token'] ?? ''; ?>">
                        <?php endif; ?>
                        
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group mb-3">
                                        <label for="refund_amount">Refund Amount <span class="text-danger">*</span></label>
                                        <div class="input-group">
                                            <span class="input-group-text"><?php echo CURRENCY_SYMBOL; ?></span>
                                            <input type="number" class="form-control" id="refund_amount" name="refund_amount" 
                                                   value="<?php echo $payment['amount'] ?? 0; ?>" step="0.01" min="0" 
                                                   max="<?php echo $payment['amount'] ?? 0; ?>" required>
                                        </div>
                                        <small class="text-muted">Maximum: <?php echo format_currency($payment['amount'] ?? 0); ?></small>
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="form-group mb-3">
                                        <label for="refund_method_id">Refund Method <span class="text-danger">*</span></label>
                                        <select class="form-select" id="refund_method_id" name="refund_method_id" required>
                                            <option value="">Select Method</option>
                                            <?php foreach ($refund_methods as $method): ?>
                                                <option value="<?php echo $method['payment_method_id'] ?? 0; ?>">
                                                    <?php echo htmlspecialchars($method['method_name'] ?? ''); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="form-group mb-3">
                                <label for="reason">Reason for Refund <span class="text-danger">*</span></label>
                                <select class="form-select" id="reason" name="reason" required>
                                    <option value="">Select Reason</option>
                                    <option value="Guest request">Guest request</option>
                                    <option value="Duplicate payment">Duplicate payment</option>
                                    <option value="Overpayment">Overpayment</option>
                                    <option value="Cancelled reservation">Cancelled reservation</option>
                                    <option value="Service not provided">Service not provided</option>
                                    <option value="Quality issue">Quality issue</option>
                                    <option value="Other">Other</option>
                                </select>
                            </div>
                            
                            <div class="form-group mb-3" id="other_reason_group" style="display: none;">
                                <label for="other_reason">Please specify</label>
                                <input type="text" class="form-control" id="other_reason" name="other_reason">
                            </div>
                            
                            <div class="form-group mb-3">
                                <label for="notes">Additional Notes</label>
                                <textarea class="form-control" id="notes" name="notes" rows="3"></textarea>
                            </div>
                            
                            <div class="alert alert-warning">
                                <i class="fas fa-exclamation-triangle me-2"></i>
                                <strong>Important:</strong> Processing a refund will reverse the payment and update the invoice balance. This action cannot be undone.
                            </div>
                        </div>
                        
                        <div class="card-footer">
                            <button type="submit" class="btn btn-warning">
                                <i class="fas fa-undo-alt me-1"></i> Process Refund
                            </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() {
    // Show/hide other reason field
    $('#reason').on('change', function() {
        if ($(this).val() === 'Other') {
            $('#other_reason_group').slideDown();
            $('#other_reason').prop('required', true);
        } else {
            $('#other_reason_group').slideUp();
            $('#other_reason').prop('required', false);
        }
    });
});

// Form validation
$('#refundForm').on('submit', function(e) {
    const amount = parseFloat($('#refund_amount').val()) || 0;
    const maxAmount = parseFloat($('#refund_amount').attr('max')) || 0;
    const reason = $('#reason').val();
    const otherReason = $('#other_reason').val();
    
    if (amount > maxAmount) {
        e.preventDefault();
        alert('Refund amount cannot exceed the original payment amount');
        return false;
    }
    
    if (reason === 'Other' && !otherReason) {
        e.preventDefault();
        alert('Please specify the reason for refund');
        return false;
    }
    
    return confirm('Process this refund? This action cannot be undone.');
});
</script>

<?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>';
}
?>