<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * POS Outlets 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 = 'POS Outlets Management';

// 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':
                $outlet_code = strtoupper(sanitize_input($_POST['outlet_code'] ?? ''));
                $outlet_name = sanitize_input($_POST['outlet_name'] ?? '');
                $outlet_type = sanitize_input($_POST['outlet_type'] ?? '');
                $location = sanitize_input($_POST['location'] ?? '');
                $tax_id = !empty($_POST['tax_id']) ? (int)$_POST['tax_id'] : null;
                
                if (empty($outlet_code)) {
                    $error = 'Outlet code is required';
                } elseif (empty($outlet_name)) {
                    $error = 'Outlet name is required';
                } elseif (empty($outlet_type)) {
                    $error = 'Outlet type is required';
                } else {
                    // Check if code exists
                    $exists = db_fetch_value("SELECT COUNT(*) FROM pos_outlets WHERE outlet_code = ?", [$outlet_code]);
                    if ($exists) {
                        $error = 'Outlet code already exists';
                    } else {
                        try {
                            db_insert('pos_outlets', [
                                'outlet_code' => $outlet_code,
                                'outlet_name' => $outlet_name,
                                'outlet_type' => $outlet_type,
                                'location' => $location,
                                'tax_id' => $tax_id,
                                'is_active' => 1
                            ]);
                            $message = 'Outlet created successfully';
                            audit_log($current_user['user_id'], AUDIT_CREATE, 'pos_outlets', null, null, $_POST);
                        } catch (Exception $e) {
                            $error = 'Failed to create outlet: ' . $e->getMessage();
                        }
                    }
                }
                break;
                
            case 'edit':
                $outlet_id = (int)($_POST['outlet_id'] ?? 0);
                $outlet_code = strtoupper(sanitize_input($_POST['outlet_code'] ?? ''));
                $outlet_name = sanitize_input($_POST['outlet_name'] ?? '');
                $outlet_type = sanitize_input($_POST['outlet_type'] ?? '');
                $location = sanitize_input($_POST['location'] ?? '');
                $tax_id = !empty($_POST['tax_id']) ? (int)$_POST['tax_id'] : null;
                $is_active = isset($_POST['is_active']) ? 1 : 0;
                
                if (!$outlet_id) {
                    $error = 'Invalid outlet ID';
                } elseif (empty($outlet_code)) {
                    $error = 'Outlet code is required';
                } elseif (empty($outlet_name)) {
                    $error = 'Outlet name is required';
                } elseif (empty($outlet_type)) {
                    $error = 'Outlet type is required';
                } else {
                    // Check if code exists for another outlet
                    $exists = db_fetch_value("SELECT COUNT(*) FROM pos_outlets WHERE outlet_code = ? AND outlet_id != ?", 
                                            [$outlet_code, $outlet_id]);
                    if ($exists) {
                        $error = 'Outlet code already exists';
                    } else {
                        try {
                            $old = db_fetch_one("SELECT * FROM pos_outlets WHERE outlet_id = ?", [$outlet_id]);
                            db_update('pos_outlets', [
                                'outlet_code' => $outlet_code,
                                'outlet_name' => $outlet_name,
                                'outlet_type' => $outlet_type,
                                'location' => $location,
                                'tax_id' => $tax_id,
                                'is_active' => $is_active
                            ], 'outlet_id = ?', [$outlet_id]);
                            $message = 'Outlet updated successfully';
                            audit_log($current_user['user_id'], AUDIT_UPDATE, 'pos_outlets', $outlet_id, $old, $_POST);
                        } catch (Exception $e) {
                            $error = 'Failed to update outlet: ' . $e->getMessage();
                        }
                    }
                }
                break;
                
            case 'delete':
                $outlet_id = (int)($_POST['outlet_id'] ?? 0);
                
                if (!$outlet_id) {
                    $error = 'Invalid outlet ID';
                } else {
                    // Check if outlet has products or sales
                    $product_count = db_fetch_value("SELECT COUNT(*) FROM pos_products WHERE outlet_id = ?", [$outlet_id]);
                    $sales_count = db_fetch_value("SELECT COUNT(*) FROM pos_sales WHERE outlet_id = ?", [$outlet_id]);
                    $shift_count = db_fetch_value("SELECT COUNT(*) FROM pos_shifts WHERE outlet_id = ?", [$outlet_id]);
                    
                    if ($product_count > 0 || $sales_count > 0 || $shift_count > 0) {
                        $error = 'Cannot delete outlet with associated products, sales, or shifts';
                    } else {
                        try {
                            db_delete('pos_outlets', 'outlet_id = ?', [$outlet_id]);
                            $message = 'Outlet deleted successfully';
                            audit_log($current_user['user_id'], AUDIT_DELETE, 'pos_outlets', $outlet_id);
                        } catch (Exception $e) {
                            $error = 'Failed to delete outlet: ' . $e->getMessage();
                        }
                    }
                }
                break;
        }
    }
}

// Get all outlets
$outlets = db_fetch_all("
    SELECT o.*, t.tax_name, t.tax_rate,
           (SELECT COUNT(*) FROM pos_products WHERE outlet_id = o.outlet_id) as product_count,
           (SELECT COUNT(*) FROM pos_sales WHERE outlet_id = o.outlet_id) as sales_count
    FROM pos_outlets o
    LEFT JOIN tax_rates t ON o.tax_id = t.tax_id
    ORDER BY o.outlet_name
");

// Get all 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");

// Get outlet to edit
$edit_outlet = null;
if (isset($_GET['edit'])) {
    $edit_outlet = db_fetch_one("SELECT * FROM pos_outlets WHERE outlet_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">POS Outlets Management</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">Outlets</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">
            <!-- Outlets List -->
            <div class="col-md-<?php echo $edit_outlet ? '7' : '12'; ?>">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-store mr-1"></i>
                            POS Outlets
                        </h3>
                        <div class="card-tools">
                            <button type="button" class="btn btn-sm btn-primary" data-toggle="modal" data-target="#createOutletModal">
                                <i class="fas fa-plus"></i> New Outlet
                            </button>
                        </div>
                    </div>
                    
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table table-striped table-hover">
                                <thead>
                                    <tr>
                                        <th>Code</th>
                                        <th>Name</th>
                                        <th>Type</th>
                                        <th>Location</th>
                                        <th>Default Tax</th>
                                        <th>Products</th>
                                        <th>Sales</th>
                                        <th>Status</th>
                                        <th width="100">Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($outlets as $outlet): ?>
                                    <tr>
                                        <td><strong><?php echo escape_html($outlet['outlet_code']); ?></strong></td>
                                        <td><?php echo escape_html($outlet['outlet_name']); ?></td>
                                        <td>
                                            <?php 
                                            $types = unserialize(OUTLET_TYPES);
                                            echo $types[$outlet['outlet_type']] ?? ucfirst($outlet['outlet_type']);
                                            ?>
                                        </td>
                                        <td><?php echo escape_html($outlet['location'] ?: '-'); ?></td>
                                        <td>
                                            <?php if ($outlet['tax_id']): ?>
                                                <?php echo escape_html($outlet['tax_name']); ?> (<?php echo $outlet['tax_rate']; ?>%)
                                            <?php else: ?>
                                                <span class="text-muted">No default</span>
                                            <?php endif; ?>
                                        </td>
                                        <td class="text-center"><?php echo $outlet['product_count']; ?></td>
                                        <td class="text-center"><?php echo $outlet['sales_count']; ?></td>
                                        <td>
                                            <?php if ($outlet['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 $outlet['outlet_id']; ?>" class="btn btn-sm btn-warning">
                                                <i class="fas fa-edit"></i>
                                            </a>
                                            <?php if ($outlet['product_count'] == 0 && $outlet['sales_count'] == 0): ?>
                                                <button type="button" class="btn btn-sm btn-danger" 
                                                        onclick="deleteOutlet(<?php echo $outlet['outlet_id']; ?>, '<?php echo escape_html($outlet['outlet_name']); ?>')">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Edit Form -->
            <?php if ($edit_outlet): ?>
            <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 Outlet: <?php echo escape_html($edit_outlet['outlet_code']); ?>
                        </h3>
                    </div>
                    
                    <form method="POST">
                        <?php echo csrf_field(); ?>
                        <input type="hidden" name="action" value="edit">
                        <input type="hidden" name="outlet_id" value="<?php echo $edit_outlet['outlet_id']; ?>">
                        
                        <div class="card-body">
                            <div class="form-group">
                                <label for="edit_outlet_code">Outlet Code <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="edit_outlet_code" name="outlet_code" 
                                       value="<?php echo escape_html($edit_outlet['outlet_code']); ?>" 
                                       maxlength="20" required>
                                <small class="text-muted">Unique identifier, e.g., MAIN-REST</small>
                            </div>
                            
                            <div class="form-group">
                                <label for="edit_outlet_name">Outlet Name <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="edit_outlet_name" name="outlet_name" 
                                       value="<?php echo escape_html($edit_outlet['outlet_name']); ?>" required>
                            </div>
                            
                            <div class="form-group">
                                <label for="edit_outlet_type">Outlet Type <span class="text-danger">*</span></label>
                                <select class="form-control" id="edit_outlet_type" name="outlet_type" required>
                                    <?php 
                                    $types = unserialize(OUTLET_TYPES);
                                    foreach ($types as $value => $label):
                                    ?>
                                        <option value="<?php echo $value; ?>" <?php echo $edit_outlet['outlet_type'] == $value ? 'selected' : ''; ?>>
                                            <?php echo $label; ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="form-group">
                                <label for="edit_location">Location</label>
                                <input type="text" class="form-control" id="edit_location" name="location" 
                                       value="<?php echo escape_html($edit_outlet['location']); ?>" 
                                       placeholder="e.g., Ground Floor, Pool Area">
                            </div>
                            
                            <div class="form-group">
                                <label for="edit_tax_id">Default Tax Rate</label>
                                <select class="form-control" id="edit_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 $edit_outlet['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="edit_is_active" name="is_active"
                                           <?php echo $edit_outlet['is_active'] ? 'checked' : ''; ?>>
                                    <label class="custom-control-label" for="edit_is_active">Active</label>
                                </div>
                                <small class="text-muted">Inactive outlets cannot be used for POS transactions</small>
                            </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="?" class="btn btn-secondary">
                                <i class="fas fa-times mr-1"></i> Cancel
                            </a>
                        </div>
                    </form>
                </div>
            </div>
            <?php endif; ?>
        </div>
    </div>
</section>

<!-- Create Outlet Modal -->
<div class="modal fade" id="createOutletModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-primary">
                <h5 class="modal-title">Create New POS Outlet</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="outlet_code">Outlet Code <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="outlet_code" name="outlet_code" 
                               maxlength="20" required placeholder="e.g., MAIN-REST">
                        <small class="text-muted">Unique identifier, uppercase letters and hyphens recommended</small>
                    </div>
                    
                    <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" 
                               required placeholder="e.g., Main Restaurant">
                    </div>
                    
                    <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 
                            $types = unserialize(OUTLET_TYPES);
                            foreach ($types as $value => $label):
                            ?>
                                <option value="<?php echo $value; ?>"><?php echo $label; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="location">Location</label>
                        <input type="text" class="form-control" id="location" name="location" 
                               placeholder="e.g., Ground Floor, Pool Area">
                    </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 escape_html($tax['tax_name']); ?> (<?php echo $tax['tax_rate']; ?>%)
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <small class="text-muted">Can be overridden per product</small>
                    </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 Outlet</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Delete Outlet Modal -->
<div class="modal fade" id="deleteOutletModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-danger">
                <h5 class="modal-title">Delete Outlet</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 outlet <strong id="deleteOutletName"></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="deleteOutletForm">
                    <?php echo csrf_field(); ?>
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="outlet_id" id="deleteOutletId">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-danger">Delete Outlet</button>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
function deleteOutlet(outletId, outletName) {
    $('#deleteOutletId').val(outletId);
    $('#deleteOutletName').text(outletName);
    $('#deleteOutletModal').modal('show');
}

// Auto-capitalize outlet code
$('#outlet_code, #edit_outlet_code').on('input', function() {
    this.value = this.value.toUpperCase();
});
</script>

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