<?php

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../classes/Branch.php';
require_once __DIR__ . '/../../classes/Sales.php';


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


$auth = new Auth($conn);


if (!isset($_SESSION['user_id'])) {
    header('Location: ../../login.php');
    exit();
}


$userRole = $_SESSION['role'] ?? null;
$userBranchId = null;


if (isset($_SESSION['branch_id'])) {
    $userBranchId = $_SESSION['branch_id'];
} elseif (isset($_SESSION['user_branch_id'])) {
    $userBranchId = $_SESSION['user_branch_id'];
} elseif (isset($_SESSION['branch'])) {
    $userBranchId = $_SESSION['branch'];
} else {

    $sql = "SELECT branch_id FROM users WHERE user_id = :user_id";
    $stmt = $conn->prepare($sql);
    $stmt->bindParam(':user_id', $_SESSION['user_id'], PDO::PARAM_INT);
    $stmt->execute();
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($user && $user['branch_id']) {
        $userBranchId = $user['branch_id'];

        $_SESSION['branch_id'] = $userBranchId;
    }
}


$allowedRoles = ['branch', 'sales', 'warehouse', 'assistant'];
$isAdmin = $auth->isSuperAdmin($_SESSION['user_id']);
$canView = $isAdmin || (in_array($userRole, $allowedRoles) && $userBranchId);

if (!$canView) {
    header('Location: ../../unauthorized.php');
    exit;
}


$branch = new Branch($conn);
$sales = new Sales($conn);


$branchId = null;
if ($isAdmin) {
    $branchId = isset($_GET['branch_id']) ? intval($_GET['branch_id']) : null;
} else {

    $branchId = $userBranchId;
}


$branchDetails = null;
if ($branchId) {
    $branchDetails = $branch->getBranchById($branchId);
    if (!$branchDetails) {

        header('Location: sales.php');
        exit;
    }
}


$branches = [];
if (!$branchId) {
    $branchesResult = $branch->getAllBranches();
    $branches = $branchesResult->fetchAll(PDO::FETCH_ASSOC);
}


$reports = [];
$sql = "SELECT wr.*, b.branch_name, u.username as verified_by_name
        FROM weekly_reports wr
        JOIN branches b ON wr.branch_id = b.branch_id
        LEFT JOIN users u ON wr.verified_by = u.user_id";

if ($branchId) {
    $sql .= " WHERE wr.branch_id = :branch_id";
}

$sql .= " ORDER BY wr.week_start_date DESC";

$stmt = $conn->prepare($sql);

if ($branchId) {
    $stmt->bindParam(':branch_id', $branchId, PDO::PARAM_INT);
}

$stmt->execute();
$reports = $stmt->fetchAll(PDO::FETCH_ASSOC);


$filteredReports = $reports;


$reportTotals = [];
foreach ($filteredReports as $report) {
    $weekStart = $report['week_start_date'];
    $weekEnd = date('Y-m-d', strtotime($weekStart . ' +6 days'));


    $sql = "SELECT SUM(total_price) as total_sales
            FROM sold_items
            WHERE branch_id = :branch_id
            AND COALESCE(is_ims_income, 1) = 1
            AND DATE(sold_at) BETWEEN :start_date AND :end_date";

    $stmt = $conn->prepare($sql);
    $stmt->bindParam(':branch_id', $report['branch_id'], PDO::PARAM_INT);
    $stmt->bindParam(':start_date', $weekStart);
    $stmt->bindParam(':end_date', $weekEnd);
    $stmt->execute();

    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    $reportTotals[$report['report_id']] = $result['total_sales'] ?: 0;
}
?>

<?php include '../../includes/header.php'; ?>
    <style>
        .report-table {
            margin-top: 20px;
        }
        .report-row {
            cursor: pointer;
        }
        .report-row:hover {
            background-color: #f5f5f5;
        }
        .status-badge {
            font-size: 0.8rem;
            padding: 0.25rem 0.5rem;
            border-radius: 20px;
        }
        .back-btn {
            margin-bottom: 20px;
        }
        .no-reports {
            text-align: center;
            padding: 50px;
            color: #6c757d;
        }
    </style>

    <div class="container mt-4">
        <?php if ($branchDetails): ?>
            <div class="row">
                <div class="col-12">
                    <?php if ($isAdmin): ?>
                        <a href="sales.php" class="btn btn-secondary back-btn">
                            <i class="fas fa-arrow-left"></i> Back to All Branches
                        </a>
                    <?php else: ?>
                        <?php

                        $dashboardUrl = '../../unauthorized.php';
                        if ($userRole === 'branch') {
                            $dashboardUrl = '../dashboard/branch.php';
                        } elseif ($userRole === 'warehouse') {
                            $dashboardUrl = '../dashboard/warehouse.php';
                        } elseif ($userRole === 'assistant') {
                            $dashboardUrl = '../dashboard/assistant.php';
                        }
                        ?>
                        <a href="<?php echo $dashboardUrl; ?>" class="btn btn-secondary back-btn">
                            <i class="fas fa-arrow-left"></i> Back to Dashboard
                        </a>
                    <?php endif; ?>
                </div>
            </div>
            <div class="row mb-4">
                <div class="col-12">
                    <h2><?php echo htmlspecialchars($branchDetails['branch_name']); ?> - Weekly Reports</h2>
                </div>
            </div>
        <?php else: ?>
            <div class="row mb-4">
                <div class="col-12">
                    <h2>All Branch Weekly Reports</h2>
                </div>
            </div>
        <?php endif; ?>



        <?php if (empty($filteredReports)): ?>
            <div class="no-reports">
                <i class="fas fa-file-alt fa-3x mb-3"></i>
                <h4>No reports found</h4>
                <p>No reports found for the selected criteria.</p>
            </div>
        <?php else: ?>
            <div class="table-responsive report-table">
                <table class="table table-hover">
                    <thead class="table-light">
                        <tr>
                            <?php if (!$branchId): ?>
                                <th>Branch</th>
                            <?php endif; ?>
                            <th>Week</th>
                            <th>Total Sales</th>
                            <th>Submitted</th>
                            <th>Verified On</th>
                            <th>Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($filteredReports as $report): ?>
                        <tr class="report-row" onclick="window.location='view_report.php?report_id=<?php echo $report['report_id']; ?>'">
                            <?php if (!$branchId): ?>
                                <td><?php echo htmlspecialchars($report['branch_name']); ?></td>
                            <?php endif; ?>
                            <td>
                                <?php echo date('M d', strtotime($report['week_start_date'])); ?> -
                                <?php echo date('M d, Y', strtotime($report['week_start_date'] . ' +6 days')); ?>
                            </td>
                            <td>MWK <?php echo number_format($report['total_sales'], 2); ?></td>
                            <td><?php echo date('M d, Y', strtotime($report['created_at'])); ?></td>
                            <td>
                                <?php if ($report['verification_status'] === 'verified'): ?>
                                    <?php echo date('M d, Y', strtotime($report['verified_at'])); ?>
                                    <br>
                                    <small class="text-muted">by <?php echo htmlspecialchars($report['verified_by_name']); ?></small>
                                <?php else: ?>
                                    -
                                <?php endif; ?>
                            </td>
                            <td>
                                <span class="badge bg-success status-badge">
                                    Verified
                                </span>
                            </td>
                            <td>
                                <a href="view_report.php?report_id=<?php echo $report['report_id']; ?>" class="btn btn-primary btn-sm">
                                    <i class="fas fa-eye"></i> View 
                                </a>
								 <a href="edit_report.php?report_id=<?php echo $report['report_id']; ?>" class="btn btn-primary btn-sm">
                                    <i class="fas fa-eye"></i> Edit 
                                </a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>

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