<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Edit POS Outlet
 * Developer: JOACHIM'S INNOTECH
 */

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

// Require authentication and permission
require_auth();
require_permission('pos.outlets.manage');

// Set page title
$page_title = 'Edit POS Outlet';

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

// Get outlet ID from URL
$outlet_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if (!$outlet_id) {
    set_flash_message('danger', 'Invalid outlet ID');
    redirect('index.php');
}

// Get outlet data
$outlet = db_fetch_one("SELECT * FROM pos_outlets WHERE outlet_id = ?", [$outlet_id]);

if (!$outlet) {
    set_flash_message('danger', 'Outlet not found');
    redirect('index.php');
}

// Get tax rates for dropdown
$tax_rates = db_fetch_all("SELECT tax_id, tax_name, tax_rate FROM tax_rates WHERE is_active = 1 ORDER BY tax_name");

// Outlet types
$outlet_types = unserialize(OUTLET_TYPES);

// Handle form submission
$errors = [];
$form_data = [
    'outlet_code' => $outlet['outlet_code'],
    'outlet_name' => $outlet['outlet_name'],
    'outlet_type' => $outlet['outlet_type'],
    'location' => $outlet['location'],
    'tax_id' => $outlet['tax_id'],
    'is_active' => $outlet['is_active']
];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf_token($_POST[CSRF_TOKEN_NAME] ?? '')) {
        $errors[] = 'Invalid security token. Please try again.';
    } else {
        // Get and validate input
        $form_data['outlet_code'] = strtoupper(sanitize_input($_POST['outlet_code'] ?? ''));
        $form_data['outlet_name'] = sanitize_input($_POST['outlet_name'] ?? '');
        $form_data['outlet_type'] = sanitize_input($_POST['outlet_type'] ?? '');
        $form_data['location'] = sanitize_input($_POST['location'] ?? '');
        $form_data['tax_id'] = !empty($_POST['tax_id']) ? (int)$_POST['tax_id'] : null;
        $form_data['is_active'] = isset($_POST['is_active']) ? 1 : 0;
        
        // Validate required fields
        if (empty($form_data['outlet_code'])) {
            $errors[] = 'Outlet code is required';
        } elseif (strlen($form_data['outlet_code']) > 20) {
            $errors[] = 'Outlet code must not exceed 20 characters';
        }
        
        if (empty($form_data['outlet_name'])) {
            $errors[] = 'Outlet name is required';
        } elseif (strlen($form_data['outlet_name']) > 50) {
            $errors[] = 'Outlet name must not exceed 50 characters';
        }
        
        if (empty($form_data['outlet_type'])) {
            $errors[] = 'Outlet type is required';
        }
        
        // Check uniqueness
        if (empty($errors)) {
            $exists = db_fetch_value("SELECT COUNT(*) FROM pos_outlets WHERE outlet_code = ? AND outlet_id != ?", 
                                     [$form_data['outlet_code'], $outlet_id]);
            if ($exists > 0) {
                $errors[] = 'Outlet code already exists';
            }
        }
        
        // Update outlet
        if (empty($errors)) {
            try {
                begin_transaction();
                
                $update_data = [
                    'outlet_code' => $form_data['outlet_code'],
                    'outlet_name' => $form_data['outlet_name'],
                    'outlet_type' => $form_data['outlet_type'],
                    'location' => $form_data['location'] ?: null,
                    'tax_id' => $form_data['tax_id'],
                    'is_active' => $form_data['is_active']
                ];
                
                db_update('pos_outlets', $update_data, 'outlet_id = ?', [$outlet_id]);
                
                // Audit log
                audit_log($current_user['user_id'], AUDIT_UPDATE, 'pos_outlets', $outlet_id, $outlet, $update_data);
                
                commit_transaction();
                
                set_flash_message('success', 'POS outlet updated successfully');
                redirect('index.php');
                
            } catch (Exception $e) {
                rollback_transaction();
                $errors[] = 'Failed to update outlet: ' . $e->getMessage();
                log_message("Outlet update failed: " . $e->getMessage(), 'ERROR');
            }
        }
    }
}

// Include header
require_once dirname(__DIR__, 3) . '/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">Edit POS Outlet: <?php echo escape_html($outlet['outlet_name']); ?></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('pos/dashboard.php'); ?>">POS</a></li>
                    <li class="breadcrumb-item"><a href="index.php">Outlets</a></li>
                    <li class="breadcrumb-item active">Edit</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 mr-2"></i>
                        <strong>Please fix the following errors:</strong>
                        <ul class="mt-2 mb-0">
                            <?php foreach ($errors as $error): ?>
                                <li><?php echo $error; ?></li>
                            <?php endforeach; ?>
                        </ul>
                        <button type="button" class="close" data-dismiss="alert">&times;</button>
                    </div>
                <?php endif; ?>

                <!-- Edit Form -->
                <div class="card card-warning">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-edit mr-1"></i>
                            Edit POS Outlet
                        </h3>
                    </div>
                    
                    <form method="POST" id="editForm">
                        <?php echo csrf_field(); ?>
                        
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="outlet_code">Outlet Code <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" id="outlet_code" name="outlet_code" 
                                               value="<?php echo escape_html($form_data['outlet_code']); ?>" 
                                               maxlength="20" required>
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="outlet_name">Outlet Name <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" id="outlet_name" name="outlet_name" 
                                               value="<?php echo escape_html($form_data['outlet_name']); ?>" 
                                               maxlength="50" required>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="outlet_type">Outlet Type <span class="text-danger">*</span></label>
                                        <select class="form-control" id="outlet_type" name="outlet_type" required>
                                            <option value="">Select Type</option>
                                            <?php foreach ($outlet_types as $value => $label): ?>
                                                <option value="<?php echo $value; ?>" <?php echo $form_data['outlet_type'] == $value ? 'selected' : ''; ?>>
                                                    <?php echo $label; ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="location">Location</label>
                                        <input type="text" class="form-control" id="location" name="location" 
                                               value="<?php echo escape_html($form_data['location']); ?>">
                                    </div>
                                </div>
                            </div>
                            
                            <div class="form-group">
                                <label for="tax_id">Default Tax Rate</label>
                                <select class="form-control" id="tax_id" name="tax_id">
                                    <option value="">No Default Tax</option>
                                    <?php foreach ($tax_rates as $tax): ?>
                                        <option value="<?php echo $tax['tax_id']; ?>" <?php echo $form_data['tax_id'] == $tax['tax_id'] ? 'selected' : ''; ?>>
                                            <?php echo escape_html($tax['tax_name']); ?> (<?php echo $tax['tax_rate']; ?>%)
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="form-group">
                                <div class="custom-control custom-switch">
                                    <input type="checkbox" class="custom-control-input" id="is_active" name="is_active"
                                           <?php echo $form_data['is_active'] ? 'checked' : ''; ?>>
                                    <label class="custom-control-label" for="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 Outlet
                            </button>
                            <a href="index.php" class="btn btn-secondary">
                                <i class="fas fa-times mr-1"></i> Cancel
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</section>

<script>
$(document).ready(function() {
    // Auto-capitalize outlet code
    $('#outlet_code').on('input', function() {
        this.value = this.value.toUpperCase();
    });
    
    // Check code availability
    let codeTimeout;
    $('#outlet_code').on('input', function() {
        clearTimeout(codeTimeout);
        const code = $(this).val();
        const originalCode = '<?php echo $outlet['outlet_code']; ?>';
        
        if (code.length < 2 || code === originalCode) return;
        
        codeTimeout = setTimeout(function() {
            $.get('<?php echo base_url('api/check-outlet-code.php'); ?>', { 
                code: code,
                exclude: <?php echo $outlet_id; ?>
            }, function(response) {
                const $code = $('#outlet_code');
                if (response.exists) {
                    $code.addClass('is-invalid');
                    if ($code.next('.invalid-feedback').length === 0) {
                        $code.after('<div class="invalid-feedback">Outlet code already exists</div>');
                    }
                } else {
                    $code.removeClass('is-invalid');
                    $code.next('.invalid-feedback').remove();
                }
            });
        }, 500);
    });
});
</script>

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