<?php

include '../../includes/header.php';


if (!$auth->isSuperAdmin($_SESSION['user_id']) &&
    !$auth->isWarehousePersonnel($_SESSION['user_id']) &&
    !$auth->isBranchManager($_SESSION['user_id'])) {
    header('Location: ../../unauthorized.php');
    exit;
}


$database = new Database();
$conn = $database->getConnection();


require_once __DIR__ . '/../../classes/StockTaking.php';
$stockTaking = new StockTaking($conn);

$canViewAllStockTakingSessions = $auth->isSuperAdmin($_SESSION['user_id']) || $auth->isWarehousePersonnel($_SESSION['user_id']);

$branches = [];
try {
    if (!$canViewAllStockTakingSessions) {

        $userBranch = $auth->getUserBranch($_SESSION['user_id']);
        $branchSql = "SELECT branch_id, branch_name FROM branches WHERE branch_id = :branch_id";
        $branchStmt = $conn->prepare($branchSql);
        $branchStmt->bindValue(':branch_id', $userBranch, PDO::PARAM_INT);
    } else {

        $branchSql = "SELECT branch_id, branch_name FROM branches ORDER BY branch_name";
        $branchStmt = $conn->prepare($branchSql);
    }
    $branchStmt->execute();
    $branches = $branchStmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    error_log("Error fetching branches: " . $e->getMessage());
}


$userRole = $stockTaking->getUserRole($_SESSION['user_id']);


$completionMessage = '';
if (isset($_GET['completed']) && isset($_GET['session_id'])) {
    $completedSessionId = (int)$_GET['session_id'];
    $completionMessage = '<div class="alert alert-success"><i class="fas fa-check-circle"></i> Stock taking session #' . $completedSessionId . ' has been completed successfully! All participants can now view the final report.</div>';
}


$message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['start_session'])) {
    $branchId = (int)$_POST['branch_id'];
    $notes = trim($_POST['notes'] ?? '');


    if (!$canViewAllStockTakingSessions) {
        $userBranch = $auth->getUserBranch($_SESSION['user_id']);
        if ($userBranch != $branchId) {
            $message = '<div class="alert alert-danger">You can only start sessions for your own branch.</div>';
        } else {
            try {
                $sessionId = $stockTaking->startSessionDual($branchId, $_SESSION['user_id'], $userRole, $notes);
                if ($sessionId) {
                    $message = '<div class="alert alert-success">Stock taking session initiation recorded! Waiting for the other party to start. <a href="stocktaking_dashboard.php">Refresh to check status</a></div>';
                } else {
                    $message = '<div class="alert alert-danger">Failed to start stock taking session. Please try again.</div>';
                }
            } catch (Exception $e) {
                $message = '<div class="alert alert-danger">Error: ' . $e->getMessage() . ' <a href="stocktaking_dashboard.php">View active sessions</a></div>';
            }
        }
    } else {

        try {
            $sessionId = $stockTaking->startSessionDual($branchId, $_SESSION['user_id'], $userRole, $notes);
            if ($sessionId) {
                $message = '<div class="alert alert-success">Stock taking session initiation recorded! Waiting for branch manager to start. <a href="stocktaking_dashboard.php">Refresh to check status</a></div>';
            } else {
                $message = '<div class="alert alert-danger">Failed to start stock taking session. Please try again.</div>';
            }
        } catch (Exception $e) {
            $message = '<div class="alert alert-danger">Error: ' . $e->getMessage() . ' <a href="stocktaking_dashboard.php">View active sessions</a></div>';
        }
    }
}


$allSessions = [];
try {
    if (!$canViewAllStockTakingSessions) {

        $userBranch = $auth->getUserBranch($_SESSION['user_id']);
        $sql = "SELECT s.*,
                       b.branch_name,
                       u.username as auditor_name,
                       admin_user.username as admin_started_name,
                       branch_user.username as branch_started_name,
                       admin_verifier.username as admin_verified_name,
                       branch_verifier.username as branch_verified_name
                FROM stock_taking_sessions s
                JOIN branches b ON s.branch_id = b.branch_id
                JOIN users u ON s.auditor_id = u.user_id
                LEFT JOIN users admin_user ON s.admin_started_by = admin_user.user_id
                LEFT JOIN users branch_user ON s.branch_started_by = branch_user.user_id
                LEFT JOIN users admin_verifier ON s.admin_verified_by = admin_verifier.user_id
                LEFT JOIN users branch_verifier ON s.branch_verified_by = branch_verifier.user_id
                WHERE s.branch_id = :branch_id
                ORDER BY s.created_at DESC";
        $stmt = $conn->prepare($sql);
        $stmt->bindValue(':branch_id', $userBranch, PDO::PARAM_INT);
    } else {

        $sql = "SELECT s.*,
                       b.branch_name,
                       u.username as auditor_name,
                       admin_user.username as admin_started_name,
                       branch_user.username as branch_started_name,
                       admin_verifier.username as admin_verified_name,
                       branch_verifier.username as branch_verified_name
                FROM stock_taking_sessions s
                JOIN branches b ON s.branch_id = b.branch_id
                JOIN users u ON s.auditor_id = u.user_id
                LEFT JOIN users admin_user ON s.admin_started_by = admin_user.user_id
                LEFT JOIN users branch_user ON s.branch_started_by = branch_user.user_id
                LEFT JOIN users admin_verifier ON s.admin_verified_by = admin_verifier.user_id
                LEFT JOIN users branch_verifier ON s.branch_verified_by = branch_verifier.user_id
                ORDER BY s.created_at DESC";
        $stmt = $conn->prepare($sql);
    }
    $stmt->execute();
    $allSessions = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    error_log("Error fetching stock taking sessions: " . $e->getMessage());
}
?>

<style>
    .dashboard-card {
        background: #fff;
        border-radius: 8px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        margin-bottom: 20px;
    }

    .dashboard-header {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        padding: 20px;
        border-radius: 8px 8px 0 0;
    }

    .session-card {
        border: 1px solid #e9ecef;
        border-radius: 8px;
        margin-bottom: 15px;
        transition: box-shadow 0.3s ease;
    }

    .session-card:hover {
        box-shadow: 0 4px 15px rgba(0,0,0,0.1);
    }

    .status-badge {
        padding: 4px 8px;
        border-radius: 4px;
        font-size: 0.8em;
        font-weight: bold;
    }

    .status-pending-start { background: #fd7e14; color: white; }
    .status-in-progress { background: #ffc107; color: #212529; }
    .status-completed { background: #28a745; color: white; }
    .status-cancelled { background: #dc3545; color: white; }

    .progress-bar {
        height: 8px;
        border-radius: 4px;
    }

    .table th {
        border-top: none;
        font-weight: 600;
        color: #495057;
        font-size: 0.9rem;
        vertical-align: middle;
    }

    .table td {
        vertical-align: middle;
        padding: 12px;
    }

    .status-badge {
        display: inline-block;
        padding: 4px 8px;
        border-radius: 12px;
        font-size: 0.75rem;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.5px;
    }

    .table-responsive {
        border-radius: 8px;
        overflow: hidden;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    }

    .table {
        margin-bottom: 0;
    }

    .table thead th {
        background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
        border-bottom: 2px solid #dee2e6;
    }

    .table tbody tr:hover {
        background-color: #f8f9fa;
    }

    .progress {
        margin-bottom: 0;
        background-color: #e9ecef;
    }

    .progress-bar {
        font-size: 0.7rem;
        font-weight: 600;
    }
</style>

<div class="container-fluid mt-4">
    <div class="row">
        <div class="col-12">
            <h2><i class="fas fa-clipboard-check"></i> Stock Taking Dashboard</h2>
            <p class="text-muted">Manage physical inventory verification sessions</p>
        </div>
    </div>

    <?php if (!empty($message)): ?>
        <div class="row">
            <div class="col-12">
                <?php echo $message; ?>
            </div>
        </div>
    <?php endif; ?>

    <?php if (!empty($completionMessage)): ?>
        <div class="row">
            <div class="col-12">
                <?php echo $completionMessage; ?>
            </div>
        </div>
    <?php endif; ?>


    <?php
    $activeSessions = [];
    try {
        if (!$canViewAllStockTakingSessions) {
            $userBranch = $auth->getUserBranch($_SESSION['user_id']);
            $activeSql = "SELECT session_id, branch_name, session_status FROM stock_taking_sessions s
                         JOIN branches b ON s.branch_id = b.branch_id
                         WHERE s.branch_id = :branch_id AND s.session_status IN ('in_progress', 'pending_start')
                         ORDER BY s.created_at DESC";
            $activeStmt = $conn->prepare($activeSql);
            $activeStmt->bindValue(':branch_id', $userBranch, PDO::PARAM_INT);
        } else {
            $activeSql = "SELECT session_id, branch_name, session_status FROM stock_taking_sessions s
                         JOIN branches b ON s.branch_id = b.branch_id
                         WHERE s.session_status IN ('in_progress', 'pending_start')
                         ORDER BY s.created_at DESC";
            $activeStmt = $conn->prepare($activeSql);
        }
        $activeStmt->execute();
        $activeSessions = $activeStmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (Exception $e) {
        error_log("Error fetching active sessions: " . $e->getMessage());
    }

    if (!empty($activeSessions)): ?>
    <div class="row">
        <div class="col-12">
            <div class="alert alert-warning">
                <h6><i class="fas fa-exclamation-triangle"></i> Active Sessions Detected</h6>
                <p>The following sessions are currently active and may prevent starting new sessions:</p>
                <ul class="mb-2">
                    <?php foreach ($activeSessions as $active): ?>
                        <li>Session #<?php echo $active['session_id']; ?> - <?php echo htmlspecialchars($active['branch_name']); ?> (<?php echo ucfirst(str_replace('_', ' ', $active['session_status'])); ?>)</li>
                    <?php endforeach; ?>
                </ul>
                <p><strong>To start a new session, please cancel the active sessions first using the Cancel buttons in the table below.</strong></p>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <div class="row">

        <div class="col-md-6">
            <div class="dashboard-card">
                <div class="dashboard-header">
                    <h5><i class="fas fa-plus-circle"></i> Start New Session</h5>
                    <p class="mb-0">Begin physical verification for a branch</p>
                </div>
                <div class="card-body">
                    <form method="POST" action="">
                        <div class="mb-3">
                            <label for="branch_id" class="form-label">Select Branch</label>
                            <select name="branch_id" id="branch_id" class="form-select" required>
                                <option value="">Choose a branch...</option>
                                <?php foreach ($branches as $branch): ?>
                                    <option value="<?php echo $branch['branch_id']; ?>">
                                        <?php echo htmlspecialchars($branch['branch_name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="notes" class="form-label">Notes (Optional)</label>
                            <textarea name="notes" id="notes" class="form-control" rows="3"
                                      placeholder="Any special instructions or notes for this session"></textarea>
                        </div>
                        <button type="submit" name="start_session" class="btn btn-primary">
                            <i class="fas fa-play"></i> Start Stock Taking Session
                        </button>
                    </form>
                </div>
            </div>
        </div>


        <div class="col-md-6">
            <div class="dashboard-card">
                <div class="dashboard-header">
                    <h5><i class="fas fa-chart-bar"></i> Quick Statistics</h5>
                    <p class="mb-0">Overview of stock taking activities</p>
                </div>
                <div class="card-body">
                    <?php
                    try {

                        $statsSql = "SELECT
                                        COUNT(*) as total_sessions,
                                        SUM(CASE WHEN status = 'in_progress' THEN 1 ELSE 0 END) as active_sessions,
                                        SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed_sessions,
                                        AVG(total_found_items) as avg_found,
                                        AVG(total_missing_items) as avg_missing
                                     FROM stock_taking_sessions";
                        $statsStmt = $conn->prepare($statsSql);
                        $statsStmt->execute();
                        $stats = $statsStmt->fetch(PDO::FETCH_ASSOC);
                    } catch (Exception $e) {
                        $stats = ['total_sessions' => 0, 'active_sessions' => 0, 'completed_sessions' => 0];
                    }
                    ?>
                    <div class="row text-center">
                        <div class="col-6">
                            <h3 class="text-primary"><?php echo $stats['total_sessions'] ?? 0; ?></h3>
                            <p class="text-muted">Total Sessions</p>
                        </div>
                        <div class="col-6">
                            <h3 class="text-warning"><?php echo $stats['active_sessions'] ?? 0; ?></h3>
                            <p class="text-muted">Active Sessions</p>
                        </div>
                    </div>
                    <hr>
                    <div class="row text-center">
                        <div class="col-6">
                            <h3 class="text-success"><?php echo $stats['completed_sessions'] ?? 0; ?></h3>
                            <p class="text-muted">Completed</p>
                        </div>
                        <div class="col-6">
                            <h3 class="text-info"><?php echo round($stats['avg_found'] ?? 0, 1); ?></h3>
                            <p class="text-muted">Avg Items Found</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>


    <div class="row">
        <div class="col-12">
            <div class="dashboard-card">
                <div class="dashboard-header">
                    <h5><i class="fas fa-history"></i> All Stock Taking Sessions</h5>
                    <p class="mb-0">Every stock taking session available to your account</p>
                </div>
                <div class="card-body">
                    <?php if (empty($allSessions)): ?>
                        <div class="text-center text-muted py-4">
                            <i class="fas fa-inbox fa-3x mb-3"></i>
                            <p>No stock taking sessions found.</p>
                            <p>Start your first session above!</p>
                        </div>
                    <?php else: ?>
                        <div class="table-responsive">
                            <table id="stockTakingSessionsTable" class="table table-hover table-striped">
                                <thead class="table-light">
                                    <tr>
                                        <th><i class="fas fa-hashtag"></i> Session ID</th>
                                        <th><i class="fas fa-building"></i> Branch</th>
                                        <th><i class="fas fa-calendar"></i> Date</th>
                                        <th><i class="fas fa-user"></i> Auditor</th>
                                        <th><i class="fas fa-info-circle"></i> Status</th>
                                        <th><i class="fas fa-chart-bar"></i> Progress/Results</th>
                                        <th><i class="fas fa-cogs"></i> Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($allSessions as $session): ?>
                                        <tr>
                                            <td data-order="<?php echo (int)$session['session_id']; ?>">
                                                <strong>#<?php echo $session['session_id']; ?></strong>
                                            </td>
                                            <td>
                                                <strong><?php echo htmlspecialchars($session['branch_name']); ?></strong>
                                            </td>
                                            <td>
                                                <?php echo date('M j, Y', strtotime($session['session_date'])); ?>
                                                <br>
                                                <small class="text-muted"><?php echo date('H:i', strtotime($session['created_at'])); ?></small>
                                            </td>
                                            <td>
                                                <?php echo htmlspecialchars($session['auditor_name']); ?>
                                            </td>
                                            <td>
                                                <span class="status-badge status-<?php echo str_replace('_', '-', $session['session_status']); ?>">
                                                    <?php echo ucfirst(str_replace('_', ' ', $session['session_status'])); ?>
                                                </span>
                                                <?php if ($session['session_status'] === 'pending_start'): ?>
                                                    <br><small class="text-muted">
                                                        <?php
                                                        $startedBy = [];
                                                        if ($session['admin_started_by']) $startedBy[] = 'Admin';
                                                        if ($session['branch_started_by']) $startedBy[] = 'Branch';
                                                        echo implode(' & ', $startedBy) . ' started';
                                                        ?>
                                                    </small>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <?php if ($session['status'] === 'in_progress'): ?>
                                                    <div class="progress" style="height: 20px;">
                                                        <div class="progress-bar bg-primary" role="progressbar"
                                                             style="width: <?php echo $session['total_system_items'] > 0 ? round(($session['total_found_items'] + $session['total_missing_items']) / $session['total_system_items'] * 100, 1) : 0; ?>%"
                                                             aria-valuenow="<?php echo $session['total_found_items'] + $session['total_missing_items']; ?>"
                                                             aria-valuemin="0" aria-valuemax="<?php echo $session['total_system_items']; ?>">
                                                            <?php echo $session['total_found_items'] + $session['total_missing_items']; ?>/<?php echo $session['total_system_items']; ?>
                                                        </div>
                                                    </div>
                                                <?php elseif ($session['status'] === 'completed'): ?>
                                                    <div class="text-center">
                                                        <div class="row text-center">
                                                            <div class="col-4">
                                                                <span class="text-success"><i class="fas fa-check"></i></span><br>
                                                                <small class="text-muted"><?php echo $session['total_found_items']; ?> Found</small>
                                                            </div>
                                                            <div class="col-4">
                                                                <span class="text-danger"><i class="fas fa-times"></i></span><br>
                                                                <small class="text-muted"><?php echo $session['total_missing_items']; ?> Missing</small>
                                                            </div>
                                                            <div class="col-4">
                                                                <span class="text-info"><i class="fas fa-plus"></i></span><br>
                                                                <small class="text-muted"><?php echo $session['total_extra_items']; ?> Extra</small>
                                                            </div>
                                                        </div>
                                                    </div>
                                                <?php else: ?>
                                                    <span class="text-muted">-</span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <div class="btn-group" role="group">
                                                    <?php if ($session['session_status'] === 'pending_start'): ?>
                                                        <?php if ($userRole === 'admin' && !$session['admin_started_by']): ?>
                                                            <button type="button" class="btn btn-sm btn-warning"
                                                                    onclick="startSession(<?php echo $session['session_id']; ?>, 'admin')">
                                                                <i class="fas fa-play"></i> Start (Admin)
                                                            </button>
                                                        <?php elseif ($userRole === 'branch_manager' && !$session['branch_started_by']): ?>
                                                            <button type="button" class="btn btn-sm btn-warning"
                                                                    onclick="startSession(<?php echo $session['session_id']; ?>, 'branch_manager')">
                                                                <i class="fas fa-play"></i> Start (Branch)
                                                            </button>
                                                        <?php else: ?>
                                                            <span class="text-muted small">Waiting for other party</span>
                                                        <?php endif; ?>
                                                    <?php elseif ($session['session_status'] === 'in_progress'): ?>
                                                        <a href="verify_items.php?session_id=<?php echo $session['session_id']; ?>"
                                                           class="btn btn-sm btn-primary" title="Continue Verification">
                                                            <i class="fas fa-play"></i> Continue
                                                        </a>
                                                    <?php elseif ($session['session_status'] === 'completed'): ?>
                                                        <a href="session_report.php?session_id=<?php echo $session['session_id']; ?>"
                                                           class="btn btn-sm btn-success" title="View Report">
                                                            <i class="fas fa-eye"></i> Report
                                                        </a>
                                                    <?php endif; ?>

                                                    <?php

                                                    $canCancel = false;
                                                    if ($canViewAllStockTakingSessions) {
                                                        $canCancel = in_array($session['session_status'], ['pending_start', 'in_progress']);
                                                    } elseif ($auth->isBranchManager($_SESSION['user_id'])) {
                                                        $userBranch = $auth->getUserBranch($_SESSION['user_id']);
                                                        $canCancel = $session['branch_id'] == $userBranch &&
                                                                    in_array($session['session_status'], ['pending_start', 'in_progress']);
                                                    }

                                                    if ($canCancel): ?>
                                                        <button type="button" class="btn btn-sm btn-danger"
                                                                onclick="cancelSession(<?php echo $session['session_id']; ?>)"
                                                                title="Cancel this session">
                                                            <i class="fas fa-times"></i> Cancel
                                                        </button>
                                                    <?php endif; ?>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    if ($.fn.DataTable && $('#stockTakingSessionsTable').length) {
        $('#stockTakingSessionsTable').DataTable({
            order: [[0, 'desc']],
            pageLength: -1,
            lengthMenu: [[-1, 25, 50, 100], ['All', 25, 50, 100]],
            language: {
                search: 'Search sessions:',
                lengthMenu: 'Show _MENU_ sessions',
                info: 'Showing _START_ to _END_ of _TOTAL_ sessions',
                emptyTable: 'No stock taking sessions found.'
            }
        });
    }
});

function startSession(sessionId, userRole) {
    if (confirm('Are you sure you want to start this stock taking session?')) {

        const button = event.target.closest('button');
        const originalHtml = button.innerHTML;
        button.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Starting...';
        button.disabled = true;


        const formData = new FormData();
        formData.append('session_id', sessionId);
        formData.append('user_role', userRole);
        formData.append('action', 'start_session');


        fetch('start_session_dual.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {

                alert('Session started successfully! The session is now active.');
                location.reload();
            } else {
                alert('Error: ' + (data.message || 'Failed to start session'));

                button.innerHTML = originalHtml;
                button.disabled = false;
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Network error occurred');

            button.innerHTML = originalHtml;
            button.disabled = false;
        });
    }
}

function cancelSession(sessionId) {
    if (confirm('Are you sure you want to cancel this stock taking session? This action cannot be undone and all progress will be lost.')) {

        const button = event.target.closest('button');
        const originalHtml = button.innerHTML;
        button.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Cancelling...';
        button.disabled = true;


        const formData = new FormData();
        formData.append('session_id', sessionId);
        formData.append('action', 'cancel_session');


        fetch('cancel_session.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {

                alert('Session cancelled successfully!');
                location.reload();
            } else {
                alert('Error: ' + (data.message || 'Failed to cancel session'));

                button.innerHTML = originalHtml;
                button.disabled = false;
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Network error occurred');

            button.innerHTML = originalHtml;
            button.disabled = false;
        });
    }
}
</script>

<?php include '../../includes/footer.php'; ?>
