<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Payment Methods Management
 * Developer: JOACHIM'S INNOTECH
 */

// Initialize system
require_once dirname(__DIR__, 2) . '/config/config.php';
require_once dirname(__DIR__, 2) . '/config/constants.php';
require_once dirname(__DIR__, 2) . '/config/database.php';
require_once dirname(__DIR__, 2) . '/config/helpers.php';
require_once dirname(__DIR__, 2) . '/config/auth.php';
require_once dirname(__DIR__, 2) . '/config/csrf.php';

// Require authentication and permission
require_auth();
require_permission('settings.edit');

// Set page title
$page_title = 'Payment Methods';

// Get current user
$current_user = current_user();

// Handle form submissions
$message = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf_token($_POST[CSRF_TOKEN_NAME] ?? '')) {
        $error = 'Invalid security token. Please try again.';
    } else {
        $action = $_POST['action'] ?? '';
        
        switch ($action) {
            case 'create':
                $method_code = strtoupper(sanitize_input($_POST['method_code'] ?? ''));
                $method_name = sanitize_input($_POST['method_name'] ?? '');
                $method_type = sanitize_input($_POST['method_type'] ?? '');
                $requires_approval = isset($_POST['requires_approval']) ? 1 : 0;
                $sort_order = (int)($_POST['sort_order'] ?? 0);
                
                if (empty($method_code)) {
                    $error = 'Method code is required';
                } elseif (empty($method_name)) {
                    $error = 'Method name is required';
                } elseif (empty($method_type)) {
                    $error = 'Method type is required';
                } else {
                    // Check if code exists
                    $exists = db_fetch_value("SELECT COUNT(*) FROM payment_methods WHERE method_code = ?", [$method_code]);
                    if ($exists) {
                        $error = 'Payment method code already exists';
                    } else {
                        try {
                            db_insert('payment_methods', [
                                'method_code' => $method_code,
                                'method_name' => $method_name,
                                'method_type' => $method_type,
                                'requires_approval' => $requires_approval,
                                'sort_order' => $sort_order,
                                'is_active' => 1
                            ]);
                            $message = 'Payment method created successfully';
                            audit_log($current_user['user_id'], AUDIT_CREATE, 'payment_methods', null, null, $_POST);
                        } catch (Exception $e) {
                            $error = 'Failed to create payment method: ' . $e->getMessage();
                        }
                    }
                }
                break;
                
            case 'edit':
                $method_id = (int)($_POST['method_id'] ?? 0);
                $method_code = strtoupper(sanitize_input($_POST['method_code'] ?? ''));
                $method_name = sanitize_input($_POST['method_name'] ?? '');
                $method_type = sanitize_input($_POST['method_type'] ?? '');
                $requires_approval = isset($_POST['requires_approval']) ? 1 : 0;
                $sort_order = (int)($_POST['sort_order'] ?? 0);
                $is_active = isset($_POST['is_active']) ? 1 : 0;
                
                if (!$method_id) {
                    $error = 'Invalid method ID';
                } elseif (empty($method_code)) {
                    $error = 'Method code is required';
                } elseif (empty($method_name)) {
                    $error = 'Method name is required';
                } elseif (empty($method_type)) {
                    $error = 'Method type is required';
                } else {
                    // Check if code exists for another method
                    $exists = db_fetch_value("SELECT COUNT(*) FROM payment_methods WHERE method_code = ? AND payment_method_id != ?", 
                                            [$method_code, $method_id]);
                    if ($exists) {
                        $error = 'Payment method code already exists';
                    } else {
                        try {
                            $old = db_fetch_one("SELECT * FROM payment_methods WHERE payment_method_id = ?", [$method_id]);
                            db_update('payment_methods', [
                                'method_code' => $method_code,
                                'method_name' => $method_name,
                                'method_type' => $method_type,
                                'requires_approval' => $requires_approval,
                                'sort_order' => $sort_order,
                                'is_active' => $is_active
                            ], 'payment_method_id = ?', [$method_id]);
                            $message = 'Payment method updated successfully';
                            audit_log($current_user['user_id'], AUDIT_UPDATE, 'payment_methods', $method_id, $old, $_POST);
                        } catch (Exception $e) {
                            $error = 'Failed to update payment method: ' . $e->getMessage();
                        }
                    }
                }
                break;
                
            case 'delete':
                $method_id = (int)($_POST['method_id'] ?? 0);
                
                if (!$method_id) {
                    $error = 'Invalid method ID';
                } else {
                    // Check if method is used in payments
                    $payment_count = db_fetch_value("SELECT COUNT(*) FROM payments WHERE payment_method_id = ?", [$method_id]);
                    $sales_count = db_fetch_value("SELECT COUNT(*) FROM pos_sales WHERE payment_method_id = ?", [$method_id]);
                    
                    if ($payment_count > 0 || $sales_count > 0) {
                        $error = 'Cannot delete payment method that has been used in transactions';
                    } else {
                        try {
                            db_delete('payment_methods', 'payment_method_id = ?', [$method_id]);
                            $message = 'Payment method deleted successfully';
                            audit_log($current_user['user_id'], AUDIT_DELETE, 'payment_methods', $method_id);
                        } catch (Exception $e) {
                            $error = 'Failed to delete payment method: ' . $e->getMessage();
                        }
                    }
                }
                break;
                
            case 'update_order':
                $orders = $_POST['order'] ?? [];
                foreach ($orders as $index => $method_id) {
                    db_update('payment_methods', ['sort_order' => $index + 1], 'payment_method_id = ?', [$method_id]);
                }
                $message = 'Sort order updated successfully';
                break;
        }
    }
}

// Get all payment methods
$payment_methods = db_fetch_all("
    SELECT * FROM payment_methods 
    ORDER BY sort_order, method_name
");

// Get method types for dropdown
$method_types = unserialize(PAYMENT_METHOD_TYPES);

// Get method to edit
$edit_method = null;
if (isset($_GET['edit'])) {
    $edit_method = db_fetch_one("SELECT * FROM payment_methods WHERE payment_method_id = ?", [(int)$_GET['edit']]);
}

// Include header
require_once dirname(__DIR__, 2) . '/views/partials/header.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">Payment Methods</h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="<?php echo base_url('dashboard.php'); ?>">Home</a></li>
                    <li class="breadcrumb-item"><a href="<?php echo base_url('admin/dashboard.php'); ?>">Admin</a></li>
                    <li class="breadcrumb-item"><a href="<?php echo base_url('admin/settings/index.php'); ?>">Settings</a></li>
                    <li class="breadcrumb-item active">Payment Methods</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- Messages -->
        <?php if ($message): ?>
            <div class="alert alert-success alert-dismissible fade show">
                <i class="fas fa-check-circle mr-2"></i>
                <?php echo $message; ?>
                <button type="button" class="close" data-dismiss="alert">&times;</button>
            </div>
        <?php endif; ?>
        
        <?php if ($error): ?>
            <div class="alert alert-danger alert-dismissible fade show">
                <i class="fas fa-exclamation-circle mr-2"></i>
                <?php echo $error; ?>
                <button type="button" class="close" data-dismiss="alert">&times;</button>
            </div>
        <?php endif; ?>

        <div class="row">
            <!-- Payment Methods List -->
            <div class="col-md-<?php echo $edit_method ? '7' : '12'; ?>">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-credit-card mr-1"></i>
                            Payment Methods
                        </h3>
                        <div class="card-tools">
                            <button type="button" class="btn btn-sm btn-primary" data-toggle="modal" data-target="#createMethodModal">
                                <i class="fas fa-plus"></i> New Method
                            </button>
                        </div>
                    </div>
                    
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table table-striped table-hover" id="methodsTable">
                                <thead>
                                    <tr>
                                        <th width="50">#</th>
                                        <th>Code</th>
                                        <th>Name</th>
                                        <th>Type</th>
                                        <th>Requires Approval</th>
                                        <th>Status</th>
                                        <th width="120">Actions</th>
                                    </tr>
                                </thead>
                                <tbody class="sortable">
                                    <?php foreach ($payment_methods as $method): ?>
                                    <tr data-id="<?php echo $method['payment_method_id']; ?>">
                                        <td class="sort-handle">
                                            <i class="fas fa-grip-vertical text-muted"></i>
                                            <span class="badge badge-secondary"><?php echo $method['sort_order']; ?></span>
                                        </td>
                                        <td><strong><?php echo escape_html($method['method_code']); ?></strong></td>
                                        <td><?php echo escape_html($method['method_name']); ?></td>
                                        <td>
                                            <?php echo $method_types[$method['method_type']] ?? ucfirst($method['method_type']); ?>
                                        </td>
                                        <td>
                                            <?php if ($method['requires_approval']): ?>
                                                <span class="badge badge-warning">Yes</span>
                                            <?php else: ?>
                                                <span class="badge badge-success">No</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php if ($method['is_active']): ?>
                                                <span class="badge badge-success">Active</span>
                                            <?php else: ?>
                                                <span class="badge badge-danger">Inactive</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <a href="?edit=<?php echo $method['payment_method_id']; ?>" class="btn btn-sm btn-warning">
                                                <i class="fas fa-edit"></i>
                                            </a>
                                            <?php if ($method['payment_method_id'] <= 9): ?>
                                                <span class="badge badge-info" title="System method - cannot delete">System</span>
                                            <?php else: ?>
                                                <button type="button" class="btn btn-sm btn-danger" 
                                                        onclick="deleteMethod(<?php echo $method['payment_method_id']; ?>, '<?php echo escape_html($method['method_name']); ?>')">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                    <div class="card-footer">
                        <button type="button" class="btn btn-info" onclick="saveOrder()">
                            <i class="fas fa-save mr-1"></i> Save Sort Order
                        </button>
                        <small class="text-muted ml-2">Drag and drop rows to reorder</small>
                    </div>
                </div>
            </div>

            <!-- Edit Form -->
            <?php if ($edit_method): ?>
            <div class="col-md-5">
                <div class="card card-warning">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-edit mr-1"></i>
                            Edit Method: <?php echo escape_html($edit_method['method_code']); ?>
                        </h3>
                    </div>
                    
                    <form method="POST">
                        <?php echo csrf_field(); ?>
                        <input type="hidden" name="action" value="edit">
                        <input type="hidden" name="method_id" value="<?php echo $edit_method['payment_method_id']; ?>">
                        
                        <div class="card-body">
                            <div class="form-group">
                                <label for="edit_method_code">Method Code <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="edit_method_code" name="method_code" 
                                       value="<?php echo escape_html($edit_method['method_code']); ?>" 
                                       maxlength="20" required>
                                <small class="text-muted">Unique identifier, e.g., CASH, VISA, MOMO</small>
                            </div>
                            
                            <div class="form-group">
                                <label for="edit_method_name">Method Name <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="edit_method_name" name="method_name" 
                                       value="<?php echo escape_html($edit_method['method_name']); ?>" required>
                            </div>
                            
                            <div class="form-group">
                                <label for="edit_method_type">Method Type <span class="text-danger">*</span></label>
                                <select class="form-control" id="edit_method_type" name="method_type" required>
                                    <?php foreach ($method_types as $value => $label): ?>
                                        <option value="<?php echo $value; ?>" 
                                                <?php echo $edit_method['method_type'] == $value ? 'selected' : ''; ?>>
                                            <?php echo $label; ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="form-group">
                                <label for="edit_sort_order">Sort Order</label>
                                <input type="number" class="form-control" id="edit_sort_order" name="sort_order" 
                                       value="<?php echo $edit_method['sort_order']; ?>" min="0">
                            </div>
                            
                            <div class="form-group">
                                <div class="custom-control custom-checkbox">
                                    <input type="checkbox" class="custom-control-input" id="edit_requires_approval" name="requires_approval"
                                           <?php echo $edit_method['requires_approval'] ? 'checked' : ''; ?>>
                                    <label class="custom-control-label" for="edit_requires_approval">
                                        Requires Approval
                                    </label>
                                </div>
                                <small class="text-muted">Check if this payment method needs manager approval</small>
                            </div>
                            
                            <div class="form-group">
                                <div class="custom-control custom-switch">
                                    <input type="checkbox" class="custom-control-input" id="edit_is_active" name="is_active"
                                           <?php echo $edit_method['is_active'] ? 'checked' : ''; ?>>
                                    <label class="custom-control-label" for="edit_is_active">Active</label>
                                </div>
                            </div>
                        </div>
                        
                        <div class="card-footer">
                            <button type="submit" class="btn btn-warning">
                                <i class="fas fa-save mr-1"></i> Update Method
                            </button>
                            <a href="?" class="btn btn-secondary">
                                <i class="fas fa-times mr-1"></i> Cancel
                            </a>
                        </div>
                    </form>
                </div>
            </div>
            <?php endif; ?>
        </div>
    </div>
</section>

<!-- Create Method Modal -->
<div class="modal fade" id="createMethodModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-primary">
                <h5 class="modal-title">Create Payment Method</h5>
                <button type="button" class="close" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            
            <form method="POST">
                <?php echo csrf_field(); ?>
                <input type="hidden" name="action" value="create">
                
                <div class="modal-body">
                    <div class="form-group">
                        <label for="method_code">Method Code <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="method_code" name="method_code" 
                               maxlength="20" required placeholder="e.g., CASH, VISA">
                        <small class="text-muted">Unique identifier, uppercase recommended</small>
                    </div>
                    
                    <div class="form-group">
                        <label for="method_name">Method Name <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="method_name" name="method_name" 
                               required placeholder="e.g., Cash, Visa Card">
                    </div>
                    
                    <div class="form-group">
                        <label for="method_type">Method Type <span class="text-danger">*</span></label>
                        <select class="form-control" id="method_type" name="method_type" required>
                            <option value="">Select Type</option>
                            <?php foreach ($method_types as $value => $label): ?>
                                <option value="<?php echo $value; ?>"><?php echo $label; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="sort_order">Sort Order</label>
                        <input type="number" class="form-control" id="sort_order" name="sort_order" value="0" min="0">
                    </div>
                    
                    <div class="form-group">
                        <div class="custom-control custom-checkbox">
                            <input type="checkbox" class="custom-control-input" id="requires_approval" name="requires_approval">
                            <label class="custom-control-label" for="requires_approval">
                                Requires Approval
                            </label>
                        </div>
                    </div>
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Create Method</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Delete Method Modal -->
<div class="modal fade" id="deleteMethodModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-danger">
                <h5 class="modal-title">Delete Payment Method</h5>
                <button type="button" class="close" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <p>Are you sure you want to delete payment method <strong id="deleteMethodName"></strong>?</p>
                <p class="text-danger"><i class="fas fa-exclamation-triangle mr-1"></i> This action cannot be undone.</p>
            </div>
            <div class="modal-footer">
                <form method="POST" id="deleteMethodForm">
                    <?php echo csrf_field(); ?>
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="method_id" id="deleteMethodId">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-danger">Delete Method</button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Sortable UI -->
<script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js"></script>

<script>
$(document).ready(function() {
    // Initialize sortable
    const sortable = new Sortable(document.querySelector('.sortable'), {
        handle: '.sort-handle',
        animation: 150,
        onEnd: function() {
            updateOrderNumbers();
        }
    });
    
    // Auto-capitalize method code
    $('#method_code, #edit_method_code').on('input', function() {
        this.value = this.value.toUpperCase();
    });
});

function updateOrderNumbers() {
    $('.sortable tr').each(function(index) {
        $(this).find('.badge-secondary').text(index + 1);
    });
}

function saveOrder() {
    const order = [];
    $('.sortable tr').each(function() {
        order.push($(this).data('id'));
    });
    
    $.post('<?php echo base_url('admin/settings/payment-methods.php'); ?>', {
        action: 'update_order',
        order: order,
        csrf_token: '<?php echo csrf_token(); ?>'
    }, function(response) {
        if (response.status === 'success') {
            alert('Sort order updated successfully');
        } else {
            alert('Failed to update sort order');
        }
    }).fail(function() {
        alert('Failed to update sort order');
    });
}

function deleteMethod(methodId, methodName) {
    $('#deleteMethodId').val(methodId);
    $('#deleteMethodName').text(methodName);
    $('#deleteMethodModal').modal('show');
}
</script>

<style>
.sort-handle {
    cursor: grab;
}
.sort-handle:active {
    cursor: grabbing;
}
.sortable tr {
    cursor: default;
}
</style>

<?php
// Include footer
require_once dirname(__DIR__, 2) . '/views/partials/footer.php';
?>