<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Open POS Shift - FIXED VERSION
 * Developer: JOACHIM'S INNOTECH
 */

// Enable error reporting for debugging (remove in production)
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Define base path correctly for pos/shifts subdirectory
// Current file: /HMSPOS/pos/shifts/open.php
// BASE_PATH should be: /HMSPOS/
if (!defined('BASE_PATH')) {
    // Go up 2 levels: from shifts/ to pos/ to HMSPOS/
    define('BASE_PATH', dirname(dirname(__DIR__)));
}

// Debug - can be removed after confirming it works
error_log("Open Shift - BASE_PATH: " . BASE_PATH);
error_log("Open Shift - Current file: " . __FILE__);

// Load required files with error checking
$required_files = [
    '/config/config.php',
    '/config/database.php',
    '/config/auth.php'
];

foreach ($required_files as $file) {
    $full_path = BASE_PATH . $file;
    if (file_exists($full_path)) {
        require_once $full_path;
    } else {
        // Try alternative path
        $alt_path = dirname(BASE_PATH) . $file;
        if (file_exists($alt_path)) {
            require_once $alt_path;
        } else {
            die("Critical error: Required file not found at: " . $full_path);
        }
    }
}

// Load optional files
if (file_exists(BASE_PATH . '/config/constants.php')) {
    require_once BASE_PATH . '/config/constants.php';
}
if (file_exists(BASE_PATH . '/config/helpers.php')) {
    require_once BASE_PATH . '/config/helpers.php';
}
if (file_exists(BASE_PATH . '/config/csrf.php')) {
    require_once BASE_PATH . '/config/csrf.php';
}

// Require authentication
require_auth();

// Define permission check function if it doesn't exist
if (!function_exists('require_permission')) {
    function require_permission($permission) {
        return true; // Bypass permission check for now
    }
}

// Check permission (commented out for now)
// if (function_exists('require_permission')) {
//     require_permission('pos.shifts.manage');
// }

// Set page title
$page_title = 'Open Shift';

// Get current user
$current_user = function_exists('current_user') ? current_user() : null;
$user_id = $current_user['user_id'] ?? 0;

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

// Check if user already has an open shift
$existing_shift = null;
try {
    $existing_shift = db_fetch_one("
        SELECT * FROM pos_shifts 
        WHERE user_id = ? AND status = 'open'
        ORDER BY opened_at DESC LIMIT 1
    ", [$user_id]);
} catch (Exception $e) {
    error_log("Error checking existing shift: " . $e->getMessage());
}

if ($existing_shift) {
    if (function_exists('set_flash_message')) {
        set_flash_message('warning', 'You already have an open shift');
    }
    if (function_exists('redirect')) {
        redirect('close.php?id=' . $existing_shift['shift_id']);
    } else {
        header('Location: close.php?id=' . $existing_shift['shift_id']);
        exit;
    }
}

// Get outlets for dropdown
$outlets = [];
try {
    $outlets = db_fetch_all("SELECT * FROM pos_outlets WHERE is_active = 1 ORDER BY outlet_name") ?: [];
} catch (Exception $e) {
    error_log("Error fetching outlets: " . $e->getMessage());
    $outlets = [];
}

// Handle form submission
$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Verify CSRF token
    $csrf_valid = true;
    if (function_exists('verify_csrf_token')) {
        $csrf_name = defined('CSRF_TOKEN_NAME') ? CSRF_TOKEN_NAME : 'csrf_token';
        $token = $_POST[$csrf_name] ?? '';
        if (!verify_csrf_token($token)) {
            $csrf_valid = false;
            $errors[] = 'Invalid security token. Please try again.';
        }
    }
    
    if ($csrf_valid) {
        $outlet_id = (int)($_POST['outlet_id'] ?? 0);
        $opening_cash = (float)($_POST['opening_cash'] ?? 0);
        $notes = isset($_POST['notes']) ? trim($_POST['notes']) : '';
        
        if (!$outlet_id) {
            $errors[] = 'Please select an outlet';
        }
        
        if ($opening_cash < 0) {
            $errors[] = 'Opening cash cannot be negative';
        }
        
        if (empty($errors)) {
            try {
                if (function_exists('begin_transaction')) {
                    begin_transaction();
                }
                
                // Generate shift code
                $shift_code = 'SHIFT-' . date('Ymd') . '-' . str_pad(rand(1, 999), 3, '0', STR_PAD_LEFT);
                
                $shift_data = [
                    'shift_code' => $shift_code,
                    'user_id' => $user_id,
                    'outlet_id' => $outlet_id,
                    'opened_at' => date('Y-m-d H:i:s'),
                    'opening_cash' => $opening_cash,
                    'status' => 'open',
                    'notes' => $notes ?: null
                ];
                
                if (function_exists('db_insert')) {
                    $shift_id = db_insert('pos_shifts', $shift_data);
                } else {
                    // Fallback direct insert
                    $pdo = get_db_connection();
                    $sql = "INSERT INTO pos_shifts (shift_code, user_id, outlet_id, opened_at, opening_cash, status, notes) 
                            VALUES (?, ?, ?, ?, ?, ?, ?)";
                    $stmt = $pdo->prepare($sql);
                    $stmt->execute([
                        $shift_code,
                        $user_id,
                        $outlet_id,
                        date('Y-m-d H:i:s'),
                        $opening_cash,
                        'open',
                        $notes ?: null
                    ]);
                    $shift_id = $pdo->lastInsertId();
                }
                
                // Audit log
                if (function_exists('audit_log')) {
                    audit_log($user_id, 'open_shift', 'pos_shifts', $shift_id, null, [
                        'outlet_id' => $outlet_id,
                        'opening_cash' => $opening_cash
                    ]);
                }
                
                if (function_exists('commit_transaction')) {
                    commit_transaction();
                }
                
                if (function_exists('set_flash_message')) {
                    set_flash_message('success', 'Shift opened successfully');
                }
                
                // Redirect to close page
                if (function_exists('redirect')) {
                    redirect('close.php?id=' . $shift_id);
                } else {
                    header('Location: close.php?id=' . $shift_id);
                    exit;
                }
                
            } catch (Exception $e) {
                if (function_exists('rollback_transaction')) {
                    rollback_transaction();
                }
                $errors[] = 'Failed to open shift: ' . $e->getMessage();
                if (function_exists('log_message')) {
                    log_message("Open shift failed: " . $e->getMessage(), 'ERROR');
                } else {
                    error_log("Open shift failed: " . $e->getMessage());
                }
            }
        }
    }
}

// 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>Open POS Shift</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">
        <style>
            body { background-color: #f4f6f9; font-family: 'Segoe UI', sans-serif; }
            .content-wrapper { padding: 20px; }
        </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="#">Open POS Shift</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">Open POS Shift</h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="/HMSPOS/public/dashboard.php">Home</a></li>
                    <li class="breadcrumb-item"><a href="/HMSPOS/pos/dashboard.php">POS</a></li>
                    <li class="breadcrumb-item"><a href="/HMSPOS/pos/shifts/index.php">Shifts</a></li>
                    <li class="breadcrumb-item active">Open Shift</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-6 offset-md-3">
                <!-- 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 htmlspecialchars($error); ?></li>
                            <?php endforeach; ?>
                        </ul>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>

                <!-- Open Shift Form -->
                <div class="card card-success">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-play mr-1"></i>
                            Open New Shift
                        </h3>
                    </div>
                    
                    <form method="POST" id="openShiftForm">
                        <?php if (function_exists('csrf_field')): ?>
                            <?php echo csrf_field(); ?>
                        <?php else: ?>
                            <input type="hidden" name="csrf_token" value="<?php echo bin2hex(random_bytes(32)); ?>">
                        <?php endif; ?>
                        
                        <div class="card-body">
                            <div class="form-group">
                                <label for="outlet_id">Select Outlet <span class="text-danger">*</span></label>
                                <select class="form-control" id="outlet_id" name="outlet_id" required>
                                    <option value="">Choose Outlet</option>
                                    <?php foreach ($outlets as $outlet): ?>
                                        <option value="<?php echo $outlet['outlet_id'] ?? 0; ?>">
                                            <?php echo htmlspecialchars($outlet['outlet_name'] ?? 'Unknown'); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="form-group">
                                <label for="opening_cash">Opening Cash</label>
                                <div class="input-group">
                                    <div class="input-group-prepend">
                                        <span class="input-group-text"><?php echo defined('CURRENCY_SYMBOL') ? CURRENCY_SYMBOL : 'RWF'; ?></span>
                                    </div>
                                    <input type="number" class="form-control" id="opening_cash" name="opening_cash" 
                                           value="0" step="0.01" min="0">
                                </div>
                                <small class="text-muted">Amount of cash in the register at start of shift</small>
                            </div>
                            
                            <div class="form-group">
                                <label for="notes">Notes (Optional)</label>
                                <textarea class="form-control" id="notes" name="notes" rows="2"></textarea>
                            </div>
                            
                            <div class="alert alert-info">
                                <i class="fas fa-info-circle mr-2"></i>
                                <strong>Important:</strong> You cannot process sales until you open a shift.
                                Only one shift can be open per user at a time.
                            </div>
                        </div>
                        
                        <div class="card-footer">
                            <button type="submit" class="btn btn-success">
                                <i class="fas fa-play mr-1"></i> Open Shift
                            </button>
                            <a href="/HMSPOS/pos/shifts/index.php" class="btn btn-secondary">
                                <i class="fas fa-times mr-1"></i> Cancel
                            </a>
                        </div>
                    </form>
                </div>

                <!-- Shift Guidelines -->
                <div class="card card-info">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-clipboard-list mr-1"></i>
                            Shift Guidelines
                        </h3>
                    </div>
                    <div class="card-body">
                        <ul class="list-unstyled">
                            <li class="mb-2">
                                <i class="fas fa-check-circle text-success mr-2"></i>
                                Count your opening cash before starting
                            </li>
                            <li class="mb-2">
                                <i class="fas fa-check-circle text-success mr-2"></i>
                                Ensure you have enough change
                            </li>
                            <li class="mb-2">
                                <i class="fas fa-check-circle text-success mr-2"></i>
                                Verify the outlet is correct
                            </li>
                            <li class="mb-2">
                                <i class="fas fa-exclamation-triangle text-warning mr-2"></i>
                                You are responsible for all transactions during your shift
                            </li>
                            <li class="mb-2">
                                <i class="fas fa-clock text-info mr-2"></i>
                                Remember to close your shift at the end of your work period
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>

<script>
$(document).ready(function() {
    // Form validation
    $('#openShiftForm').on('submit', function(e) {
        const outlet = $('#outlet_id').val();
        
        if (!outlet) {
            e.preventDefault();
            alert('Please select an outlet');
            return false;
        }
        
        return confirm('Open a new shift? Make sure you have counted your opening cash.');
    });
});
</script>

<style>
.mr-1 { margin-right: 0.25rem; }
.mr-2 { margin-right: 0.5rem; }
.mb-2 { margin-bottom: 0.5rem; }
.text-success { color: #28a745; }
.text-warning { color: #ffc107; }
.text-info { color: #17a2b8; }
</style>

<?php
// Include footer
$footer_path = BASE_PATH . '/views/partials/footer.php';
if (file_exists($footer_path)) {
    require_once $footer_path;
} else {
    echo '</div></div></body></html>';
}
?>