<?php

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


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


if ($auth->isSuperAdmin($_SESSION['user_id']) || $auth->isWarehousePersonnel($_SESSION['user_id'])) {
    $userRole = 'admin';
} elseif ($auth->isBranchManager($_SESSION['user_id'])) {
    $userRole = 'branch_manager';
} elseif ($auth->isAssistant($_SESSION['user_id'])) {
    $userRole = 'assistant';
} else {
    $userRole = 'unknown';
}


$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';
require_once __DIR__ . '/../../classes/Request.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;
    }
}


error_log("Stock Taking Report: Loading session ID: $sessionId");
$report = $stockTaking->getSessionReport($sessionId);
if (isset($report['error'])) {
    error_log("Stock Taking Report: Error getting report: " . $report['error']);
    die("Error: " . $report['error']);
}
error_log("Stock Taking Report: Successfully loaded report for session $sessionId");

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

$requestMessage = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_missing_request'])) {
    if (empty($report['missing_items'])) {
        $requestMessage = '<div class="alert alert-warning">There are no missing items to send.</div>';
    } else {
        $request = new Request($conn);
        $result = ['success' => false, 'message' => 'Unable to create request.'];
        $maxRetries = 3;
        $retryCount = 0;

        do {
            $requestNumber = 'IRQF' . date('Y') . str_pad(rand(1, 9999), 4, '0', STR_PAD_LEFT);
            $result = $request->createFromStocktakingMissingItems(
                (int)$session['branch_id'],
                (int)$_SESSION['user_id'],
                $requestNumber,
                $report['missing_items'],
                $sessionId
            );
            $retryCount++;
        } while (!$result['success'] && strpos($result['message'], 'Duplicate entry') !== false && $retryCount < $maxRetries);

        if ($result['success']) {
            $alertClass = !empty($result['already_exists']) ? 'alert-info' : 'alert-success';
            $requestMessage = '<div class="alert ' . $alertClass . '">'
                . htmlspecialchars($result['message'])
                . ' <a class="alert-link" href="../sales/request_receipt.php?request_id=' . (int)$result['request_id'] . '">View request</a>'
                . '</div>';
        } else {
            $requestMessage = '<div class="alert alert-danger">Failed to create request: '
                . htmlspecialchars($result['message'])
                . '</div>';
        }
    }
}


$itemSummary = $stockTaking->getItemQuantitySummary($sessionId);
?>
<script>
	function printReport(){
		const  sessionId = "<?php echo $sessionId ?>";
		const  item_status=document.getElementById("item_status").value;
		 window.open('session_report_print.php?session_id='+sessionId+'&item_status='+item_status,'_blank');
		//alert(sessionId);
	}
</script>

<style>
    .report-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; }


    @media print {
        body {
            font-size: 12px;
            line-height: 1.4;
        }

        .report-header {
            background: #f8f9fa !important;
            color: #000 !important;
            -webkit-print-color-adjust: exact;
            color-adjust: exact;
        }

        .summary-card {
            break-inside: avoid;
        }

        .item-row {
            break-inside: avoid;
            border: 1px solid #dee2e6 !important;
            margin-bottom: 5px !important;
            page-break-inside: avoid;
        }

        .card {
            break-inside: avoid;
            page-break-inside: avoid;
        }

        .btn-group, .breadcrumb, nav, .navbar {
            display: none !important;
        }

        .container-fluid {
            margin: 0 !important;
            padding: 0 !important;
        }

        h1, h2, h3, h4, h5, h6 {
            page-break-after: avoid;
        }

        .card-body {
            max-height: none !important;
            overflow: visible !important;
        }


        .col-md-4 {
            page-break-inside: avoid;
        }

        .row + .row {
            page-break-before: always;
        }
    }
</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">Session Report</li>
                </ol>
            </nav>
        </div>
    </div>


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

    <div class="row">
        <div class="col-12">
            <div class="report-header">
                <div class="row align-items-center">
                    <div class="col-md-8">
                        <h2><i class="fas fa-clipboard-check"></i> Stock Taking Report</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>Auditor:</strong> <?php echo htmlspecialchars($session['auditor_name']); ?>
                        </p>
                        <p class="mb-0">
                            <strong>Status:</strong>
                            <span class="badge bg-success ms-2">Completed</span>
                            <strong>Completed:</strong> <?php echo date('F j, Y \a\t g:i A', strtotime($session['completed_at'])); ?>
                        </p>
                    </div>
                    <div class="col-md-4 text-md-end">
                        <div class="btn-group">
							<select id="item_status">
								<option value = "found" > Found	</option>
								<option value = "missing" > Missing	</option>
								<option value = "all" > All	</option>
							</select>
							<button type="button" class="btn btn-light" onclick="printReport()">
                                <i class="fas fa-print"></i> Print Report
                            </button>
                            <form method="POST" class="d-inline">
                                <input type="hidden" name="create_missing_request" value="1">
                                <button type="submit"
                                        class="btn btn-warning"
                                        <?php echo empty($report['missing_items']) ? 'disabled' : ''; ?>
                                        onclick="return confirm('Send all missing items from this report to Request Items?');">
                                    <i class="fas fa-paper-plane"></i> Send Missing Items
                                </button>
                            </form>
							<!--
                            <button type="button" class="btn btn-light" onclick="downloadPDF()">
                                <i class="fas fa-download"></i> Download PDF
                            </button> -->
                        </div>
                    </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-percentage"></i> Completion Rate</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">
                                        <?php
                                        $completion = $item['total_system_quantity'] > 0 ?
                                            round((($item['found_quantity'] ?? 0) + ($item['missing_quantity'] ?? 0)) / $item['total_system_quantity'] * 100, 1) : 0;
                                        $completionClass = $completion == 100 ? 'bg-success' : ($completion > 50 ? 'bg-warning' : 'bg-danger');
                                        ?>
                                        <div class="progress" style="height: 20px;">
                                            <div class="progress-bar <?php echo $completionClass; ?>" role="progressbar"
                                                 style="width: <?php echo $completion; ?>%"
                                                 aria-valuenow="<?php echo $completion; ?>" aria-valuemin="0" aria-valuemax="100">
                                                <?php echo $completion; ?>%
                                            </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>


    <?php if (!empty($session['notes'])): ?>
    <div class="row mt-4">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-sticky-note"></i> Session Notes</h5>
                </div>
                <div class="card-body">
                    <p class="mb-0"><?php echo nl2br(htmlspecialchars($session['notes'])); ?></p>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>




    <div class="row mt-4">
        <div class="col-12 text-center">
            <?php if (($session['session_status'] ?? $session['status']) === 'completed'): ?>
            <div class="btn-group">
                <?php if ($userRole === 'admin'): ?>

                    <a href="approve_report_updates.php?session_id=<?php echo $sessionId; ?>" class="btn btn-info">
                        <i class="fas fa-check-double"></i> Approve Updates
                    </a>
                <?php elseif ($userRole === 'branch_manager' || $userRole === 'assistant'): ?>

                    <a href="request_report_update.php?session_id=<?php echo $sessionId; ?>" class="btn btn-warning">
                        <i class="fas fa-edit"></i> Request Update
                    </a>
                <?php endif; ?>
            </div>
            <?php endif; ?>
        </div>
    </div>
</div>

