<?php



$message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['complete_session'])) {

    require_once __DIR__ . '/../../classes/Database.php';
    require_once __DIR__ . '/../../classes/Logger.php';
    require_once __DIR__ . '/../../classes/StockTaking.php';


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

    $sessionId = isset($_POST['session_id']) ? (int)$_POST['session_id'] : 0;

    if ($sessionId) {
        $stockTaking = new StockTaking($conn);


        $sessionData = $stockTaking->getSessionItems($sessionId);
        if (isset($sessionData['error'])) {
            $message = '<div class="alert alert-danger">Error checking session: ' . $sessionData['error'] . '</div>';
        } elseif ($sessionData['verified_items'] < $sessionData['total_items']) {
            $message = '<div class="alert alert-warning">Not all items have been verified yet. Please verify all items before completing.</div>';
        } else {

            $message = '<div class="alert alert-success">All items verified! Redirecting to preview for final verification...</div>';

            header("Location: preview_session.php?session_id=$sessionId");
            exit;
        }
    }
}

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;
}


$sessionId = isset($_GET['session_id']) ? (int)$_GET['session_id'] : 0;
if (!$sessionId) {
    header('Location: stocktaking_dashboard.php');
    exit;
}


$database = new Database();
$conn = $database->getConnection();
require_once __DIR__ . '/../../classes/StockTaking.php';
$stockTaking = new StockTaking($conn);


if (!$auth->isSuperAdmin($_SESSION['user_id'])) {
    $userBranch = $auth->getUserBranch($_SESSION['user_id']);
    $sessionSql = "SELECT branch_id FROM stock_taking_sessions WHERE session_id = :session_id";
    $sessionStmt = $conn->prepare($sessionSql);
    $sessionStmt->bindValue(':session_id', $sessionId, PDO::PARAM_INT);
    $sessionStmt->execute();
    $session = $sessionStmt->fetch(PDO::FETCH_ASSOC);

    if (!$session || $session['branch_id'] != $userBranch) {
        header('Location: stocktaking_dashboard.php');
        exit;
    }
}


$sessionData = $stockTaking->getSessionItems($sessionId);
if (isset($sessionData['error'])) {
    die("Error: " . $sessionData['error']);
}


$totalItems = $sessionData['total_items'];
$verifiedItems = $sessionData['verified_items'];
$progressPercent = $totalItems > 0 ? round(($verifiedItems / $totalItems) * 100, 1) : 0;
?>

<style>
    .verification-card {
        border: 1px solid #e9ecef;
        border-radius: 8px;
        margin-bottom: 15px;
        transition: all 0.3s ease;
    }

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

    .verification-card.verified {
        border-left: 4px solid #28a745;
        background-color: #f8fff9;
    }

    .verification-card.pending {
        border-left: 4px solid #ffc107;
    }

    .status-indicator {
        width: 12px;
        height: 12px;
        border-radius: 50%;
        display: inline-block;
        margin-right: 8px;
    }

    .status-found { background-color: #28a745; }
    .status-missing { background-color: #dc3545; }
    .status-extra { background-color: #17a2b8; }
    .status-pending { background-color: #ffc107; }

    .progress-container {
        background: #f8f9fa;
        padding: 20px;
        border-radius: 8px;
        margin-bottom: 20px;
    }

    .item-image {
        max-width: 80px;
        max-height: 80px;
        border-radius: 4px;
    }

    .verification-form {
        background: #f8f9fa;
        padding: 15px;
        border-radius: 6px;
        margin-top: 10px;
    }

    .filter-controls {
        background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
        border: 1px solid #dee2e6;
        border-radius: 8px;
    }

    .filter-controls .form-label {
        font-weight: 600;
        color: #495057;
        margin-bottom: 0.5rem;
    }

    .filter-controls .form-control,
    .filter-controls .form-select {
        border: 1px solid #ced4da;
        border-radius: 4px;
    }

    .filter-controls .form-control:focus,
    .filter-controls .form-select:focus {
        border-color: #80bdff;
        box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
    }

    .quick-filter-btn {
        transition: all 0.2s ease;
    }

    .quick-filter-btn:hover {
        transform: translateY(-1px);
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }
</style>

<div class="container-fluid mt-4">
    <div class="row">
        <div class="col-12">
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="stocktaking_dashboard.php">Stock Taking</a></li>
                    <li class="breadcrumb-item active">Verify Items</li>
                </ol>
            </nav>

            <h2><i class="fas fa-search"></i> Stock Taking Session</h2>
            <p class="text-muted">
                Branch: <strong><?php echo htmlspecialchars($sessionData['session']['branch_name'] ?? 'Unknown'); ?></strong> |
                Date: <strong><?php echo date('F j, Y', strtotime($sessionData['session']['session_date'])); ?></strong>
            </p>
        </div>
    </div>

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


    <div class="row">
        <div class="col-12">
            <div class="progress-container">
                <div class="row align-items-center">
                    <div class="col-md-8">
                        <h5>Verification Progress</h5>
                        <p class="mb-2">
                            <strong><?php echo $verifiedItems; ?></strong> of <strong><?php echo $totalItems; ?></strong> items verified
                            (<?php echo $progressPercent; ?>%)
                        </p>
                        <div class="progress">
                            <div class="progress-bar bg-success" role="progressbar"
                                 style="width: <?php echo $progressPercent; ?>%"
                                 aria-valuenow="<?php echo $progressPercent; ?>"
                                 aria-valuemin="0" aria-valuemax="100">
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4 text-md-end">
                        <div class="btn-group">
                            <button type="button" class="btn btn-outline-primary" onclick="showBulkActions()">
                                <i class="fas fa-tasks"></i> Bulk Actions
                            </button>
                            <form method="POST" style="display: inline;">
                                <input type="hidden" name="session_id" value="<?php echo $sessionId; ?>">
                                <button type="submit" name="complete_session" class="btn btn-success"
                                        onclick="return confirm('Are you sure you want to proceed to preview? This will make the session available for both admin and branch manager to review and complete the verification.')">
                                    <i class="fas fa-eye"></i> Proceed to Preview
                                </button>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>


    <div class="row mb-3">
        <div class="col-12">
            <div class="card filter-controls">
                <div class="card-body">
                    <div class="row g-3 align-items-end">
                        <div class="col-md-4">
                            <label for="searchInput" class="form-label">
                                <i class="fas fa-search"></i> Search Items
                            </label>
                            <input type="text" class="form-control" id="searchInput"
                                   placeholder="Search by item name or unique code...">
                        </div>
                        <div class="col-md-3">
                            <label for="statusFilter" class="form-label">
                                <i class="fas fa-filter"></i> Filter by Status
                            </label>
                            <select class="form-select" id="statusFilter">
                                <option value="all">All Items</option>
                                <option value="pending">Pending Only</option>
                                <option value="verified">Verified Only</option>
                                <option value="found">Found Items</option>
                                <option value="missing">Missing Items</option>
                                <option value="extra">Extra Items</option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <label for="sortBy" class="form-label">
                                <i class="fas fa-sort"></i> Sort by
                            </label>
                            <select class="form-select" id="sortBy">
                                <option value="name">Item Name</option>
                                <option value="code">Unique Code</option>
                                <option value="status">Status</option>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <button type="button" class="btn btn-outline-secondary w-100" onclick="clearFilters()">
                                <i class="fas fa-times"></i> Clear
                            </button>
                        </div>
                    </div>
                    <div class="row mt-2">
                        <div class="col-12">
                            <small class="text-muted">
                                <span id="itemCount"><?php echo count($sessionData['items']); ?></span> items total |
                                <span id="visibleCount"><?php echo count($sessionData['items']); ?></span> visible
                            </small>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>


    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <div>
                        <h5><i class="fas fa-list"></i> Items to Verify</h5>
                        <small class="text-muted">Click Found or Missing for each item</small>
                    </div>
                    <div class="btn-group" role="group">
                        <button type="button" class="btn btn-sm btn-outline-primary quick-filter-btn" onclick="showPendingOnly()">
                            <i class="fas fa-clock"></i> Show Pending
                        </button>
                        <button type="button" class="btn btn-sm btn-outline-success quick-filter-btn" onclick="showVerifiedOnly()">
                            <i class="fas fa-check"></i> Show Verified
                        </button>
                    </div>
                </div>
                <div class="card-body">
                    <?php if (empty($sessionData['items'])): ?>
                        <div class="text-center text-muted py-5">
                            <i class="fas fa-inbox fa-3x mb-3"></i>
                            <p>No items found for this branch.</p>
                        </div>
                    <?php else: ?>
                        <div class="row" id="itemsContainer">
                            <?php foreach ($sessionData['items'] as $item): ?>
                                <div class="col-md-6 col-lg-4">
                                    <div class="verification-card <?php echo $item['verification_status'] === 'pending' ? 'pending' : 'verified'; ?>">
                                        <div class="card-body">
                                            <div class="d-flex justify-content-between align-items-start mb-2">
                                                <h6 class="card-title mb-0">
                                                    <?php echo htmlspecialchars($item['item_name']); ?> <small>Details: <?php echo htmlspecialchars($item['item_details'] ?? 'N/A'); ?></small>
                                                </h6>
                                                <span class="status-indicator status-<?php echo $item['verification_status']; ?>"></span>
                                            </div>

                                            <p class="text-muted small mb-2">
                                                <strong>Code:</strong> <?php echo htmlspecialchars($item['unique_code']); ?>
                                            </p>
                                            <p class="text-muted small mb-2">
                                                <strong>Price:</strong> MWK <?php echo number_format($item['unit_price'], 2); ?>
                                            </p>

                                            <?php if ($item['verification_status'] !== 'pending'): ?>
                                                <div class="alert alert-<?php echo $item['verification_status'] === 'found' ? 'success' : 'warning'; ?> py-2">
                                                    <small>
                                                        <i class="fas fa-check-circle"></i>
                                                        <?php echo ucfirst($item['verification_status']); ?>
                                                        <?php if (!empty($item['location_found'])): ?>
                                                            at <?php echo htmlspecialchars($item['location_found']); ?>
                                                        <?php endif; ?>
                                                    </small>
                                                </div>
                                            <?php endif; ?>

                                            <div class="d-flex gap-1">
                                                <button type="button" class="btn btn-sm btn-success flex-fill"
                                                        onclick="recordVerification(<?php echo $item['item_id']; ?>, '<?php echo addslashes($item['unique_code']); ?>', 'found', this)"
                                                        <?php echo $item['verification_status'] === 'found' ? 'disabled' : ''; ?>>
                                                    <i class="fas fa-check"></i> Found
                                                </button>
                                                <button type="button" class="btn btn-sm btn-danger flex-fill"
                                                        onclick="recordVerification(<?php echo $item['item_id']; ?>, '<?php echo addslashes($item['unique_code']); ?>', 'missing', this)"
                                                        <?php echo $item['verification_status'] === 'missing' ? 'disabled' : ''; ?>>
                                                    <i class="fas fa-times"></i> Missing
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>


<script>
let allItems = <?php echo json_encode($sessionData['items']); ?>;
let filteredItems = [...allItems];

document.addEventListener('DOMContentLoaded', function() {

    const searchInput = document.getElementById('searchInput');
    const statusFilter = document.getElementById('statusFilter');
    const sortBy = document.getElementById('sortBy');


    searchInput.addEventListener('input', filterAndSortItems);
    statusFilter.addEventListener('change', filterAndSortItems);
    sortBy.addEventListener('change', filterAndSortItems);


    renderItems();
});

function recordVerification(itemId, uniqueCode, status, buttonElement) {

    const card = buttonElement.closest('.verification-card');
    const buttons = card.querySelectorAll('button');
    buttons.forEach(btn => btn.disabled = true);


    buttonElement.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Recording...';


    const formData = new FormData();
    formData.append('session_id', <?php echo $sessionId; ?>);
    formData.append('item_id', itemId);
    formData.append('unique_code', uniqueCode);
    formData.append('status', status);


    console.log('Sending AJAX request to: record_verification.php');
    fetch('record_verification.php', {
        method: 'POST',
        body: formData
    })
    .then(response => {
        console.log('Response status:', response.status);
        if (!response.ok) {
            throw new Error('HTTP error! status: ' + response.status);
        }
        return response.json();
    })
    .then(data => {
        if (data.success) {

            updateItemStatus(card, status);
            updateProgressCounters(data.data);


            const itemIndex = allItems.findIndex(item => item.item_id == itemId);
            if (itemIndex !== -1) {
                allItems[itemIndex].verification_status = status;
            }


            showToast('Verification recorded successfully!', 'success');
        } else {

            showToast(data.message || 'Failed to record verification', 'error');


            buttons.forEach(btn => btn.disabled = false);
            buttonElement.innerHTML = status === 'found' ?
                '<i class="fas fa-check"></i> Found' :
                '<i class="fas fa-times"></i> Missing';
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showToast('Network error occurred', 'error');


        buttons.forEach(btn => btn.disabled = false);
        buttonElement.innerHTML = status === 'found' ?
            '<i class="fas fa-check"></i> Found' :
            '<i class="fas fa-times"></i> Missing';
    });
}

function updateItemStatus(card, status) {

    const statusIndicator = card.querySelector('.status-indicator');
    statusIndicator.className = `status-indicator status-${status}`;


    card.classList.remove('pending', 'verified');
    card.classList.add('verified');


    const buttons = card.querySelectorAll('button');
    buttons.forEach(btn => {
        btn.disabled = true;
        if (btn.onclick.toString().includes(status)) {
            btn.innerHTML = status === 'found' ?
                '<i class="fas fa-check"></i> Found ✓' :
                '<i class="fas fa-times"></i> Missing ✓';
        } else {
            btn.innerHTML = status === 'found' ?
                '<i class="fas fa-times"></i> Missing' :
                '<i class="fas fa-check"></i> Found';
        }
    });


    const existingAlert = card.querySelector('.alert');
    if (existingAlert) {
        existingAlert.remove();
    }

    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${status === 'found' ? 'success' : 'warning'} py-2`;
    alertDiv.innerHTML = `
        <small>
            <i class="fas fa-check-circle"></i>
            ${status.charAt(0).toUpperCase() + status.slice(1)} - Recorded
        </small>
    `;

    const cardBody = card.querySelector('.card-body');
    const buttonsContainer = card.querySelector('.d-flex');
    cardBody.insertBefore(alertDiv, buttonsContainer);
}

function updateProgressCounters(data) {

    const progressBar = document.querySelector('.progress-bar');
    progressBar.style.width = data.progress_percent + '%';
    progressBar.setAttribute('aria-valuenow', data.progress_percent);


    const progressText = document.querySelector('.progress-container p');
    progressText.innerHTML = `
        <strong>${data.verified_items}</strong> of <strong>${data.total_items}</strong> items verified
        (${data.progress_percent}%)
    `;


    document.getElementById('itemCount').textContent = data.total_items;
    document.getElementById('visibleCount').textContent = data.total_items;
}

function showToast(message, type) {

    const toast = document.createElement('div');
    toast.className = `alert alert-${type === 'success' ? 'success' : 'error' ? 'danger' : 'info'} alert-dismissible fade show position-fixed`;
    toast.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
    toast.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;

    document.body.appendChild(toast);


    setTimeout(() => {
        if (toast.parentNode) {
            toast.remove();
        }
    }, 3000);
}

function filterAndSortItems() {
    const searchTerm = document.getElementById('searchInput').value.toLowerCase();
    const statusFilter = document.getElementById('statusFilter').value;
    const sortBy = document.getElementById('sortBy').value;


    filteredItems = allItems.filter(item => {

        const matchesSearch = searchTerm === '' ||
            item.item_name.toLowerCase().includes(searchTerm) || (item.item_details || '').toLowerCase().includes(searchTerm) ||
            item.unique_code.toLowerCase().includes(searchTerm);


        let matchesStatus = true;
        if (statusFilter !== 'all') {
            switch (statusFilter) {
                case 'pending':
                    matchesStatus = item.verification_status === 'pending';
                    break;
                case 'verified':
                    matchesStatus = item.verification_status !== 'pending';
                    break;
                case 'found':
                    matchesStatus = item.verification_status === 'found';
                    break;
                case 'missing':
                    matchesStatus = item.verification_status === 'missing';
                    break;
                case 'extra':
                    matchesStatus = item.verification_status === 'extra';
                    break;
            }
        }

        return matchesSearch && matchesStatus;
    });


    filteredItems.sort((a, b) => {
        switch (sortBy) {
            case 'name':
                return a.item_name.localeCompare(b.item_name);
            case 'code':
                return a.unique_code.localeCompare(b.unique_code);
            case 'status':
                const statusOrder = { 'pending': 0, 'found': 1, 'missing': 2, 'extra': 3 };
                return statusOrder[a.verification_status] - statusOrder[b.verification_status];
            default:
                return 0;
        }
    });

    renderItems();
}

function renderItems() {
    const itemsHtml = filteredItems.map(item => `
        <div class="col-md-6 col-lg-4">
            <div class="verification-card ${item.verification_status === 'pending' ? 'pending' : 'verified'}">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-start mb-2">
                        <h6 class="card-title mb-0">
                            ${escapeHtml(item.item_name)} <small>Details: ${escapeHtml(item.item_details || 'N/A')}</small>
                        </h6>
                        <span class="status-indicator status-${item.verification_status}"></span>
                    </div>

                    <p class="text-muted small mb-2">
                        <strong>Code:</strong> ${escapeHtml(item.unique_code)}
                    </p>
                    <p class="text-muted small mb-2">
                        <strong>Price:</strong> MWK ${parseFloat(item.unit_price).toLocaleString('en-US', {minimumFractionDigits: 2})}
                    </p>

                    ${item.verification_status !== 'pending' ? `
                        <div class="alert alert-${item.verification_status === 'found' ? 'success' : 'warning'} py-2">
                            <small>
                                <i class="fas fa-check-circle"></i>
                                ${item.verification_status.charAt(0).toUpperCase() + item.verification_status.slice(1)}
                                ${item.location_found ? ` at ${escapeHtml(item.location_found)}` : ''}
                            </small>
                        </div>
                    ` : ''}

                    <div class="d-flex gap-1">
                        <button type="button" class="btn btn-sm btn-success flex-fill"
                                onclick="recordVerification(${item.item_id}, '${escapeHtml(item.unique_code)}', 'found', this)"
                                ${item.verification_status === 'found' ? 'disabled' : ''}>
                            <i class="fas fa-check"></i> Found
                        </button>
                        <button type="button" class="btn btn-sm btn-danger flex-fill"
                                onclick="recordVerification(${item.item_id}, '${escapeHtml(item.unique_code)}', 'missing', this)"
                                ${item.verification_status === 'missing' ? 'disabled' : ''}>
                            <i class="fas fa-times"></i> Missing
                        </button>
                    </div>
                </div>
            </div>
        </div>
    `).join('');


    const itemsContainer = document.getElementById('itemsContainer');
    if (itemsContainer) {
        itemsContainer.innerHTML = itemsHtml;
    }


    document.getElementById('itemCount').textContent = allItems.length;
    document.getElementById('visibleCount').textContent = filteredItems.length;
}

function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

function clearFilters() {
    document.getElementById('searchInput').value = '';
    document.getElementById('statusFilter').value = 'all';
    document.getElementById('sortBy').value = 'name';
    filterAndSortItems();
}

function showPendingOnly() {
    document.getElementById('statusFilter').value = 'pending';
    filterAndSortItems();
}

function showVerifiedOnly() {
    document.getElementById('statusFilter').value = 'verified';
    filterAndSortItems();
}

function showBulkActions() {
    alert('Bulk actions feature coming soon!');
}
</script>

