<?php

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


$auth = new Auth($conn);
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;
    }
}


$userRole = $auth->isSuperAdmin($_SESSION['user_id']) || $auth->isWarehousePersonnel($_SESSION['user_id'])
    ? 'admin' : 'branch_manager';


if (!$stockTaking->canUserPerformAction($sessionId, $_SESSION['user_id'], $userRole, 'preview')) {
    echo '<div class="alert alert-warning">You cannot preview this session at this time.</div>';
    include '../../includes/footer.php';
    exit;
}


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

$session = $report['session'];
$summary = $report['summary'];


$stockTaking = new StockTaking($conn);
$itemSummary = $stockTaking->getItemQuantitySummary($sessionId);


$message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['confirm_verification'])) {
    $result = $stockTaking->recordPreview($sessionId, $_SESSION['user_id'], $userRole);
    if ($result) {
        $message = '<div class="alert alert-success">Verification completed successfully! The stock taking session has been finalized.</div>';

        header("Refresh: 3; url=stocktaking_dashboard.php");
    } else {
        $message = '<div class="alert alert-danger">Failed to complete verification. Please try again.</div>';
    }
}
?>

<style>
    .preview-header {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        padding: 30px;
        border-radius: 8px;
        margin-bottom: 30px;
    }

    .summary-card {
        border: none;
        border-radius: 8px;
        box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        transition: transform 0.3s ease;
    }

    .summary-card:hover {
        transform: translateY(-2px);
    }

    .status-found { background: linear-gradient(135deg, #28a745, #20c997); }
    .status-missing { background: linear-gradient(135deg, #dc3545, #fd7e14); }
    .status-extra { background: linear-gradient(135deg, #17a2b8, #6f42c1); }

    .item-row {
        border: 1px solid #e9ecef;
        border-radius: 6px;
        margin-bottom: 8px;
        padding: 12px;
        transition: all 0.2s ease;
    }

    .item-row:hover {
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        border-color: #dee2e6;
    }

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

    .badge-found { background: #d4edda; color: #155724; }
    .badge-missing { background: #f8d7da; color: #721c24; }
    .badge-extra { background: #d1ecf1; color: #0c5460; }

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

    .participant-badge {
        display: inline-block;
        padding: 6px 12px;
        border-radius: 20px;
        font-size: 0.8em;
        font-weight: 600;
        margin: 2px;
    }

    .participant-started { background: #d4edda; color: #155724; }
    .participant-previewed { background: #cce5ff; color: #004085; }
    .participant-verified { background: #d1ecf1; color: #0c5460; }
    .participant-pending { background: #fff3cd; color: #856404; }
</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"><a href="verify_items.php?session_id=<?php echo $sessionId; ?>">Verify Items</a></li>
                    <li class="breadcrumb-item active">Final Verification</li>
                </ol>
            </nav>
        </div>
    </div>


    <div class="row">
        <div class="col-12">
            <div class="preview-header">
                <div class="row align-items-center">
                    <div class="col-md-8">
                        <h2><i class="fas fa-check-double"></i> Final Verification - Stock Taking Session</h2>
                        <p class="mb-2">
                            <strong>Branch:</strong> <?php echo htmlspecialchars($session['branch_name']); ?> |
                            <strong>Date:</strong> <?php echo date('F j, Y', strtotime($session['session_date'])); ?> |
                            <strong>Status:</strong> <?php echo ucfirst(str_replace('_', ' ', $session['session_status'])); ?>
                        </p>
                        <p class="mb-0">
                            Please review the verification results below. Your confirmation will complete the stock taking session.
                        </p>
                    </div>
                    <div class="col-md-4 text-md-end">
                        <div class="btn-group">
                            <a href="verify_items.php?session_id=<?php echo $sessionId; ?>" class="btn btn-light">
                                <i class="fas fa-arrow-left"></i> Back to Verification
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

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


    <div class="row mb-4">
        <div class="col-12">
            <div class="participant-info">
                <h5><i class="fas fa-users"></i> Verification Progress</h5>
                <p class="text-muted">Both admin and branch manager must verify to complete the session.</p>
                <div class="row">
                    <div class="col-md-6">
                        <h6>Admin Role:</h6>
                        <?php if ($session['admin_started_by']): ?>
                            <span class="participant-badge participant-started">
                                <i class="fas fa-play"></i> Started by <?php echo htmlspecialchars($session['admin_started_name']); ?>
                            </span>
                        <?php else: ?>
                            <span class="participant-badge participant-pending">
                                <i class="fas fa-clock"></i> Not started
                            </span>
                        <?php endif; ?>

                        <?php if ($session['admin_verified_at']): ?>
                            <span class="participant-badge participant-verified">
                                <i class="fas fa-check-circle"></i> Verified by <?php echo htmlspecialchars($session['admin_started_name']); ?>
                            </span>
                        <?php else: ?>
                            <span class="participant-badge participant-pending">
                                <i class="fas fa-clock"></i> Not verified
                            </span>
                        <?php endif; ?>
                    </div>
                    <div class="col-md-6">
                        <h6>Branch Manager Role:</h6>
                        <?php if ($session['branch_started_by']): ?>
                            <span class="participant-badge participant-started">
                                <i class="fas fa-play"></i> Started by <?php echo htmlspecialchars($session['branch_started_name']); ?>
                            </span>
                        <?php else: ?>
                            <span class="participant-badge participant-pending">
                                <i class="fas fa-clock"></i> Not started
                            </span>
                        <?php endif; ?>

                        <?php if ($session['branch_verified_at']): ?>
                            <span class="participant-badge participant-verified">
                                <i class="fas fa-check-circle"></i> Verified by <?php echo htmlspecialchars($session['branch_started_name']); ?>
                            </span>
                        <?php else: ?>
                            <span class="participant-badge participant-pending">
                                <i class="fas fa-clock"></i> Not verified
                            </span>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>


    <div class="row mb-4">
        <div class="col-md-3">
            <div class="card summary-card status-found text-white">
                <div class="card-body text-center">
                    <i class="fas fa-check-circle fa-2x mb-2"></i>
                    <h3><?php echo $summary['total_found']; ?></h3>
                    <p class="mb-0">Items Found</p>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card summary-card status-missing text-white">
                <div class="card-body text-center">
                    <i class="fas fa-exclamation-triangle fa-2x mb-2"></i>
                    <h3><?php echo $summary['total_missing']; ?></h3>
                    <p class="mb-0">Items Missing</p>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card summary-card status-extra text-white">
                <div class="card-body text-center">
                    <i class="fas fa-plus-circle fa-2x mb-2"></i>
                    <h3><?php echo $summary['total_extra']; ?></h3>
                    <p class="mb-0">Extra Items</p>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card summary-card bg-secondary text-white">
                <div class="card-body text-center">
                    <i class="fas fa-database fa-2x mb-2"></i>
                    <h3><?php echo $summary['total_system']; ?></h3>
                    <p class="mb-0">System Total</p>
                </div>
            </div>
        </div>
    </div>


    <?php if (!isset($itemSummary['error']) && !empty($itemSummary)): ?>
    <div class="row mb-4">
        <div class="col-12">
            <div class="card">
                <div class="card-header bg-primary text-white">
                    <h5 class="mb-0"><i class="fas fa-chart-bar"></i> Item Quantity Summary by Name</h5>
                    <small class="text-white-50">Overview of quantities for each item type</small>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-striped table-hover">
                            <thead class="table-dark">
                                <tr>
                                    <th><i class="fas fa-tag"></i> Item Name</th>
                                    <th class="text-center"><i class="fas fa-database"></i> System Total</th>
                                    <th class="text-center"><i class="fas fa-check-circle text-success"></i> Found</th>
                                    <th class="text-center"><i class="fas fa-exclamation-triangle text-danger"></i> Missing</th>
                                    <th class="text-center"><i class="fas fa-plus-circle text-info"></i> Extra</th>
                                    <th class="text-center"><i class="fas fa-clock text-warning"></i> Pending</th>
                                    <th class="text-center"><i class="fas fa-percentage"></i> Progress</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($itemSummary as $item): ?>
                                <tr>
                                    <td>
                                        <strong><?php echo htmlspecialchars($item['item_name']); ?></strong><br><small>Details: <?php echo htmlspecialchars($item['item_details'] ?? 'N/A'); ?></small>
                                    </td>
                                    <td class="text-center">
                                        <span class="badge bg-secondary"><?php echo $item['total_system_quantity']; ?></span>
                                    </td>
                                    <td class="text-center">
                                        <span class="badge bg-success"><?php echo $item['found_quantity'] ?? 0; ?></span>
                                    </td>
                                    <td class="text-center">
                                        <span class="badge bg-danger"><?php echo $item['missing_quantity'] ?? 0; ?></span>
                                    </td>
                                    <td class="text-center">
                                        <span class="badge bg-info"><?php echo $item['extra_quantity'] ?? 0; ?></span>
                                    </td>
                                    <td class="text-center">
                                        <span class="badge bg-warning"><?php echo $item['pending_quantity'] ?? 0; ?></span>
                                    </td>
                                    <td class="text-center">
                                        <?php
                                        $progress = $item['total_system_quantity'] > 0 ?
                                            round((($item['found_quantity'] ?? 0) + ($item['missing_quantity'] ?? 0)) / $item['total_system_quantity'] * 100, 1) : 0;
                                        $progressClass = $progress == 100 ? 'bg-success' : ($progress > 50 ? 'bg-warning' : 'bg-danger');
                                        ?>
                                        <div class="progress" style="height: 20px;">
                                            <div class="progress-bar <?php echo $progressClass; ?>" role="progressbar"
                                                 style="width: <?php echo $progress; ?>%"
                                                 aria-valuenow="<?php echo $progress; ?>" aria-valuemin="0" aria-valuemax="100">
                                                <?php echo $progress; ?>%
                                            </div>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>


    <div class="row">

        <div class="col-md-4">
            <div class="card">
                <div class="card-header bg-success text-white">
                    <h5 class="mb-0"><i class="fas fa-check-circle"></i> Found Items (<?php echo count($report['found_items']); ?>)</h5>
                </div>
                <div class="card-body" style="max-height: 400px; overflow-y: auto;">
                    <?php if (empty($report['found_items'])): ?>
                        <p class="text-muted text-center">No items found</p>
                    <?php else: ?>
                        <?php foreach ($report['found_items'] as $item): ?>
                            <div class="item-row">
                                <div class="d-flex justify-content-between align-items-start">
                                    <div>
                                        <strong><?php echo htmlspecialchars($item['item_name'] ?? 'Unknown Item'); ?></strong><br><small>Details: <?php echo htmlspecialchars($item['item_details'] ?? 'N/A'); ?></small>
                                        <br><small class="text-muted">Code: <?php echo htmlspecialchars($item['unique_code']); ?></small>
                                        <?php if (!empty($item['location_found'])): ?>
                                            <br><small class="text-muted">Location: <?php echo htmlspecialchars($item['location_found']); ?></small>
                                        <?php endif; ?>
                                    </div>
                                    <span class="status-badge badge-found">Found</span>
                                </div>
                                <?php if (!empty($item['notes'])): ?>
                                    <div class="mt-2">
                                        <small class="text-muted"><?php echo htmlspecialchars($item['notes']); ?></small>
                                    </div>
                                <?php endif; ?>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>


        <div class="col-md-4">
            <div class="card">
                <div class="card-header bg-danger text-white">
                    <h5 class="mb-0"><i class="fas fa-exclamation-triangle"></i> Missing Items (<?php echo count($report['missing_items']); ?>)</h5>
                </div>
                <div class="card-body" style="max-height: 400px; overflow-y: auto;">
                    <?php if (empty($report['missing_items'])): ?>
                        <p class="text-muted text-center">No missing items</p>
                    <?php else: ?>
                        <?php foreach ($report['missing_items'] as $item): ?>
                            <div class="item-row">
                                <div class="d-flex justify-content-between align-items-start">
                                    <div>
                                        <strong><?php echo htmlspecialchars($item['item_name'] ?? 'Unknown Item'); ?></strong><br><small>Details: <?php echo htmlspecialchars($item['item_details'] ?? 'N/A'); ?></small>
                                        <br><small class="text-muted">Code: <?php echo htmlspecialchars($item['unique_code']); ?></small>
                                        <?php if (!empty($item['location_found'])): ?>
                                            <br><small class="text-muted">Last known: <?php echo htmlspecialchars($item['location_found']); ?></small>
                                        <?php endif; ?>
                                    </div>
                                    <span class="status-badge badge-missing">Missing</span>
                                </div>
                                <?php if (!empty($item['notes'])): ?>
                                    <div class="mt-2">
                                        <small class="text-muted"><?php echo htmlspecialchars($item['notes']); ?></small>
                                    </div>
                                <?php endif; ?>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>


        <div class="col-md-4">
            <div class="card">
                <div class="card-header bg-info text-white">
                    <h5 class="mb-0"><i class="fas fa-plus-circle"></i> Extra Items (<?php echo count($report['extra_items']); ?>)</h5>
                </div>
                <div class="card-body" style="max-height: 400px; overflow-y: auto;">
                    <?php if (empty($report['extra_items'])): ?>
                        <p class="text-muted text-center">No extra items</p>
                    <?php else: ?>
                        <?php foreach ($report['extra_items'] as $item): ?>
                            <div class="item-row">
                                <div class="d-flex justify-content-between align-items-start">
                                    <div>
                                        <strong><?php echo htmlspecialchars($item['item_name'] ?? 'Unknown Item'); ?></strong><br><small>Details: <?php echo htmlspecialchars($item['item_details'] ?? 'N/A'); ?></small>
                                        <br><small class="text-muted">Code: <?php echo htmlspecialchars($item['unique_code']); ?></small>
                                        <?php if (!empty($item['location_found'])): ?>
                                            <br><small class="text-muted">Found at: <?php echo htmlspecialchars($item['location_found']); ?></small>
                                        <?php endif; ?>
                                    </div>
                                    <span class="status-badge badge-extra">Extra</span>
                                </div>
                                <?php if (!empty($item['notes'])): ?>
                                    <div class="mt-2">
                                        <small class="text-muted"><?php echo htmlspecialchars($item['notes']); ?></small>
                                    </div>
                                <?php endif; ?>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>


    <div class="row mt-4">
        <div class="col-12 text-center">
            <div class="card">
                <div class="card-body">
                    <h5>Final Verification</h5>
                    <p class="text-muted">By confirming this verification, you acknowledge that you have reviewed the stock taking results above. This will complete the session.</p>
                    <form method="POST" style="display: inline;">
                        <button type="submit" name="confirm_verification" class="btn btn-success btn-lg"
                                onclick="return confirm('Are you sure you want to complete this stock taking session? This action cannot be undone.')">
                            <i class="fas fa-check-double"></i> I Have Reviewed the Results - Complete Session
                        </button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

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