<?php
/**
 * Report Controller - With Proper Cashier Restrictions
 * Fixed: getCurrentUser() visibility + Back to Reports navigation
 * Fixed: Service Analysis now shows summary + Custom Report shows location name
 */

class ReportController extends Controller {

    private $reportModel;
    private $locationModel;
    private $barberModel;

    public function __construct() {
        parent::__construct();
        $this->requireLogin();
        $this->reportModel = $this->model('Report');
        $this->locationModel = $this->model('Location');
        $this->barberModel = $this->model('Barber');
    }

    /**
     * Reports dashboard/index - NOW WORKS FOR CASHIERS TOO!
     */
    public function index() {
        $user = $this->getCurrentUser();
        $userRole = $_SESSION['role_name'] ?? '';

        // Get locations for filter (admin/superuser only)
        $locations = [];
        if (in_array($userRole, ['admin', 'superuser'])) {
            $locations = $this->locationModel->getAllLocations();
        }

        // Load business settings
        require_once __DIR__ . '/../helpers/settings_loader.php';
        $BUSINESS = loadBusinessSettings();

        // Determine available reports based on role
        $availableReports = [
            'sales' => [
                'title' => 'Sales Report',
                'description' => 'Daily sales breakdown and revenue analysis',
                'icon' => 'fas fa-chart-line',
                'url' => 'report/sales',
                'roles' => ['admin', 'superuser', 'cashier']
            ],
            'barbers' => [
                'title' => 'Barber Performance',
                'description' => 'Individual barber statistics and commissions',
                'icon' => 'fas fa-cut',
                'url' => 'report/barbers',
                'roles' => ['admin', 'superuser', 'cashier']
            ],
            'services' => [
                'title' => 'Service Analysis',
                'description' => 'Most popular services and trends',
                'icon' => 'fas fa-list-check',
                'url' => 'report/services',
                'roles' => ['admin', 'superuser'] // NOT cashier
            ],
            'locations' => [
                'title' => 'Location Comparison',
                'description' => 'Compare performance across all locations',
                'icon' => 'fas fa-map-marker-alt',
                'url' => 'report/locations',
                'roles' => ['admin', 'superuser'] // NOT cashier
            ],
            'vat' => [
                'title' => 'VAT Report',
                'description' => 'Tax calculations and compliance reporting',
                'icon' => 'fas fa-receipt',
                'url' => 'report/vat',
                'roles' => ['admin', 'superuser'] // NOT cashier
            ],
            'custom' => [
                'title' => 'Custom Report Builder',
                'description' => 'Build custom reports with flexible filters',
                'icon' => 'fas fa-sliders-h',
                'url' => 'report/custom',
                'roles' => ['admin', 'superuser'] // NOT cashier
            ]
        ];

        // Filter reports by user role
        $userReports = array_filter($availableReports, function($report) use ($userRole) {
            return in_array($userRole, $report['roles']);
        });

        $data = [
            'title' => 'Reports',
            'user' => $user,
            'locations' => $locations,
            'availableReports' => $userReports,
            'BUSINESS' => $BUSINESS
        ];

        $this->view('reports/index', $data);
    }

    /**
     * Sales Report - Available to all roles
     */
    public function sales() {
        $user = $this->getCurrentUser();
        $userRole = $_SESSION['role_name'] ?? '';

        // Get filters with cashier restrictions
        $locationId = 0;

        if ($userRole === 'cashier') {
            // Cashiers can ONLY see their assigned location
            $locationId = $user['location_id'];

            // Get requested dates (default to today)
            $dateFrom = $_GET['date_from'] ?? date('Y-m-d');
            $dateTo = $_GET['date_to'] ?? date('Y-m-d');

            // Validate: cashiers can't go back more than 7 days
            $sevenDaysAgo = date('Y-m-d', strtotime('-7 days'));
            if ($dateFrom < $sevenDaysAgo) {
                $dateFrom = $sevenDaysAgo;
            }

        } else {
            // Admin/SuperUser can see all locations and any date range
            $locationId = intval($_GET['location_id'] ?? 0);
            $dateFrom = $_GET['date_from'] ?? date('Y-m-d', strtotime('-30 days'));
            $dateTo = $_GET['date_to'] ?? date('Y-m-d');
        }

        // Get report data
        $salesData = $this->reportModel->getSalesReport($locationId, $dateFrom, $dateTo);
        $summary = $this->reportModel->getSalesSummary($locationId, $dateFrom, $dateTo);

        // Get locations for filter (only for admin/superuser)
        $locations = [];
        if (in_array($userRole, ['admin', 'superuser'])) {
            $locations = $this->locationModel->getAllLocations();
        }

        // Load business settings
        require_once __DIR__ . '/../helpers/settings_loader.php';
        $BUSINESS = loadBusinessSettings();

        $data = [
            'title' => 'Sales Report',
            'user' => $user,
            'salesData' => $salesData,
            'summary' => $summary,
            'locations' => $locations,
            'selectedLocation' => $locationId,
            'dateFrom' => $dateFrom,
            'dateTo' => $dateTo,
            'maxDaysBack' => ($userRole === 'cashier') ? 7 : 365,
            'BUSINESS' => $BUSINESS
        ];

        $this->view('reports/sales', $data);
    }

    /**
     * Barber Performance Report
     */
    public function barbers() {
        $user = $this->getCurrentUser();
        $userRole = $_SESSION['role_name'] ?? '';

        // Get filters
        $barberId = intval($_GET['barber_id'] ?? 0);
        $locationId = 0;

        if ($userRole === 'cashier') {
            // Cashiers can ONLY see their assigned location
            $locationId = $user['location_id'];

            // Get requested dates (default to today)
            $dateFrom = $_GET['date_from'] ?? date('Y-m-d');
            $dateTo = $_GET['date_to'] ?? date('Y-m-d');

            // Validate: cashiers can't go back more than 7 days
            $sevenDaysAgo = date('Y-m-d', strtotime('-7 days'));
            if ($dateFrom < $sevenDaysAgo) {
                $dateFrom = $sevenDaysAgo;
            }

        } else if ($userRole === 'barber') {
            // Barber can only see their own performance
            $barberId = $user['user_id'];
            $dateFrom = $_GET['date_from'] ?? date('Y-m-d', strtotime('-30 days'));
            $dateTo = $_GET['date_to'] ?? date('Y-m-d');

        } else {
            // Admin/Superuser can see everything
            $locationId = intval($_GET['location_id'] ?? 0);
            $dateFrom = $_GET['date_from'] ?? date('Y-m-d', strtotime('-30 days'));
            $dateTo = $_GET['date_to'] ?? date('Y-m-d');
        }

        // Get report data
        $barberData = $this->reportModel->getBarberPerformance($barberId, $dateFrom, $dateTo, $locationId);

        // Get barbers for filter
        $barbers = [];
        if (in_array($userRole, ['admin', 'superuser'])) {
            $barbers = $this->barberModel->getAllBarbers('active');
        } else if ($userRole === 'cashier') {
            // Cashiers can only see barbers at their location
            $barbers = $this->barberModel->getBarbersByLocation($locationId);
        }

        // Get locations for filter (only admin/superuser)
        $locations = [];
        if (in_array($userRole, ['admin', 'superuser'])) {
            $locations = $this->locationModel->getAllLocations();
        }

        // Load business settings
        require_once __DIR__ . '/../helpers/settings_loader.php';
        $BUSINESS = loadBusinessSettings();

        $data = [
            'title' => 'Barber Performance Report',
            'user' => $user,
            'barberData' => $barberData,
            'barbers' => $barbers,
            'locations' => $locations,
            'selectedBarber' => $barberId,
            'selectedLocation' => $locationId,
            'dateFrom' => $dateFrom,
            'dateTo' => $dateTo,
            'maxDaysBack' => ($userRole === 'cashier') ? 7 : 365,
            'BUSINESS' => $BUSINESS
        ];

        $this->view('reports/barbers', $data);
    }

    /**
     * Service Analysis Report - BLOCKED for cashiers
     * FIXED: Now passes summary and location name
     */
    public function services() {
        $user = $this->getCurrentUser();
        $userRole = $_SESSION['role_name'] ?? '';

        // BLOCK CASHIERS from this report
        if ($userRole === 'cashier') {
            $this->setFlash('You do not have permission to access Service Analysis reports.', 'error');
            $this->redirect('report');
            return;
        }

        // Get filters
        $locationId = intval($_GET['location_id'] ?? 0);
        $dateFrom = $_GET['date_from'] ?? date('Y-m-d', strtotime('-30 days'));
        $dateTo = $_GET['date_to'] ?? date('Y-m-d');

        // Get report data (now properly filtered!)
        $serviceData = $this->reportModel->getServiceAnalysis($locationId, $dateFrom, $dateTo);
        
        // Get summary statistics (NEW!)
        $summary = $this->reportModel->getServiceAnalysisSummary($locationId, $dateFrom, $dateTo);
        
        // Get location name for display (NEW!)
        $locationName = $this->reportModel->getLocationName($locationId);

        // Get locations for filter
        $locations = [];
        if (in_array($userRole, ['admin', 'superuser'])) {
            $locations = $this->locationModel->getAllLocations();
        }

        // Load business settings
        require_once __DIR__ . '/../helpers/settings_loader.php';
        $BUSINESS = loadBusinessSettings();

        $data = [
            'title' => 'Service Analysis Report',
            'user' => $user,
            'serviceData' => $serviceData,
            'summary' => $summary,              // NEW!
            'locationName' => $locationName,    // NEW!
            'locations' => $locations,
            'selectedLocation' => $locationId,
            'dateFrom' => $dateFrom,
            'dateTo' => $dateTo,
            'BUSINESS' => $BUSINESS
        ];

        $this->view('reports/services', $data);
    }

    /**
     * Location Comparison Report
     */
    public function locations() {
        $this->requireRole(['admin', 'superuser']); // Only admin can compare locations

        $user = $this->getCurrentUser();

        // Get filters
        $dateFrom = $_GET['date_from'] ?? date('Y-m-d', strtotime('-30 days'));
        $dateTo = $_GET['date_to'] ?? date('Y-m-d');

        // Get report data
        $locationData = $this->reportModel->getLocationComparison($dateFrom, $dateTo);

        // Load business settings
        require_once __DIR__ . '/../helpers/settings_loader.php';
        $BUSINESS = loadBusinessSettings();

        $data = [
            'title' => 'Location Comparison Report',
            'user' => $user,
            'locationData' => $locationData,
            'dateFrom' => $dateFrom,
            'dateTo' => $dateTo,
            'BUSINESS' => $BUSINESS
        ];

        $this->view('reports/locations', $data);
    }

    /**
     * VAT Report - BLOCKED for cashiers
     */
    public function vat() {
        $user = $this->getCurrentUser();
        $userRole = $_SESSION['role_name'] ?? '';

        // BLOCK CASHIERS from VAT report
        if ($userRole === 'cashier') {
            $this->setFlash('You do not have permission to access VAT reports.', 'error');
            $this->redirect('report');
            return;
        }

        // Get filters
        $locationId = intval($_GET['location_id'] ?? 0);
        $dateFrom = $_GET['date_from'] ?? date('Y-m-d', strtotime('-30 days'));
        $dateTo = $_GET['date_to'] ?? date('Y-m-d');

        // Get report data
        $vatData = $this->reportModel->getVATReport($locationId, $dateFrom, $dateTo);
        $summary = $this->reportModel->getVATSummary($locationId, $dateFrom, $dateTo);

        // Get locations for filter
        $locations = [];
        if (in_array($userRole, ['admin', 'superuser'])) {
            $locations = $this->locationModel->getAllLocations();
        }

        // Load business settings
        require_once __DIR__ . '/../helpers/settings_loader.php';
        $BUSINESS = loadBusinessSettings();

        $data = [
            'title' => 'VAT Report',
            'user' => $user,
            'vatData' => $vatData,
            'summary' => $summary,
            'locations' => $locations,
            'selectedLocation' => $locationId,
            'dateFrom' => $dateFrom,
            'dateTo' => $dateTo,
            'BUSINESS' => $BUSINESS
        ];

        $this->view('reports/vat', $data);
    }

    /**
     * Custom Report Builder - BLOCKED for cashiers
     * FIXED: Now passes location name and summary to view
     */
    public function custom() {
        $user = $this->getCurrentUser();
        $userRole = $_SESSION['role_name'] ?? '';

        // BLOCK CASHIERS from custom reports
        if ($userRole === 'cashier') {
            $this->setFlash('You do not have permission to access Custom Report Builder.', 'error');
            $this->redirect('report');
            return;
        }

        // Get filters
        $reportType = $_GET['report_type'] ?? 'sales';
        $locationId = intval($_GET['location_id'] ?? 0);
        $barberId = intval($_GET['barber_id'] ?? 0);
        $dateFrom = $_GET['date_from'] ?? date('Y-m-d', strtotime('-30 days'));
        $dateTo = $_GET['date_to'] ?? date('Y-m-d');

        $reportData = null;
        $summary = null;
        
        // Get location name for display (NEW!)
        $locationName = $this->reportModel->getLocationName($locationId);

        // Generate report if requested
        if (isset($_GET['generate'])) {
            switch($reportType) {
                case 'sales':
                    $reportData = $this->reportModel->getSalesReport($locationId, $dateFrom, $dateTo);
                    $summary = $this->reportModel->getSalesSummary($locationId, $dateFrom, $dateTo);
                    break;
                    
                case 'barbers':
                    $reportData = $this->reportModel->getBarberPerformance($barberId, $dateFrom, $dateTo, $locationId);
                    break;
                    
                case 'services':
                    $reportData = $this->reportModel->getServiceAnalysis($locationId, $dateFrom, $dateTo);
                    $summary = $this->reportModel->getServiceAnalysisSummary($locationId, $dateFrom, $dateTo);
                    break;
                    
                case 'vat':
                    $reportData = $this->reportModel->getVATReport($locationId, $dateFrom, $dateTo);
                    $summary = $this->reportModel->getVATSummary($locationId, $dateFrom, $dateTo);
                    break;
            }
        }

        // Get locations for filter
        $locations = [];
        if (in_array($userRole, ['admin', 'superuser'])) {
            $locations = $this->locationModel->getAllLocations();
        }

        // Get barbers for filter
        $barbers = [];
        if (in_array($userRole, ['admin', 'superuser'])) {
            $barbers = $this->barberModel->getAllBarbers('active');
        }

        // Load business settings
        require_once __DIR__ . '/../helpers/settings_loader.php';
        $BUSINESS = loadBusinessSettings();

        $data = [
            'title' => 'Custom Report Builder',
            'user' => $user,
            'reportType' => $reportType,
            'reportData' => $reportData,
            'summary' => $summary,              // NEW!
            'locationName' => $locationName,    // NEW!
            'locations' => $locations,
            'barbers' => $barbers,
            'selectedLocation' => $locationId,
            'selectedBarber' => $barberId,
            'dateFrom' => $dateFrom,
            'dateTo' => $dateTo,
            'BUSINESS' => $BUSINESS
        ];

        $this->view('reports/custom', $data);
    }

    /**
     * Generate Custom Report (AJAX)
     * FIXED: Now returns summary and location name
     */
    public function generateCustom() {
        header('Content-Type: application/json');

        $user = $this->getCurrentUser();
        $userRole = $_SESSION['role_name'] ?? '';

        // Get parameters from POST
        $reportType = $_POST['report_type'] ?? 'sales';
        $dateFrom = $_POST['date_from'] ?? date('Y-m-d', strtotime('-30 days'));
        $dateTo = $_POST['date_to'] ?? date('Y-m-d');
        $locationId = intval($_POST['location_id'] ?? 0);
        $barberId = intval($_POST['barber_id'] ?? 0);

        // Cashiers can only see their location
        if ($userRole === 'cashier') {
            $locationId = $user['location_id'];
        }

        $data = [];
        $summary = null;
        
        // Get location name (NEW!)
        $locationName = $this->reportModel->getLocationName($locationId);

        // Get data based on report type
        switch ($reportType) {
            case 'sales':
                $data = $this->reportModel->getSalesReport($locationId, $dateFrom, $dateTo);
                $summary = $this->reportModel->getSalesSummary($locationId, $dateFrom, $dateTo);
                break;
                
            case 'barbers':
                $data = $this->reportModel->getBarberPerformance($barberId, $dateFrom, $dateTo, $locationId);
                break;
                
            case 'services':
                $data = $this->reportModel->getServiceAnalysis($locationId, $dateFrom, $dateTo);
                $summary = $this->reportModel->getServiceAnalysisSummary($locationId, $dateFrom, $dateTo);
                break;
                
            case 'vat':
                $data = $this->reportModel->getVATReport($locationId, $dateFrom, $dateTo);
                $summary = $this->reportModel->getVATSummary($locationId, $dateFrom, $dateTo);
                break;
        }

        echo json_encode([
            'success' => true,
            'data' => $data,
            'summary' => $summary,          // NEW!
            'locationName' => $locationName  // NEW!
        ]);
    }

    /**
     * Export report to PDF
     */
    public function exportPDF() {
        $reportType = $_GET['type'] ?? 'sales';
        $locationId = intval($_GET['location_id'] ?? 0);
        $dateFrom = $_GET['date_from'] ?? date('Y-m-d', strtotime('-30 days'));
        $dateTo = $_GET['date_to'] ?? date('Y-m-d');

        // Load TCPDF
        require_once __DIR__ . '/../../vendor/autoload.php';

        // Create PDF
        $pdf = new TCPDF('P', 'mm', 'A4', true, 'UTF-8');

        // Set document information
        $pdf->SetCreator('Rashwan\'s Barber POS');
        $pdf->SetAuthor('Rashwan\'s Barber');
        $pdf->SetTitle(ucfirst($reportType) . ' Report');

        // Remove default header/footer
        $pdf->setPrintHeader(false);
        $pdf->setPrintFooter(false);

        // Add a page
        $pdf->AddPage();

        // Set font
        $pdf->SetFont('helvetica', '', 10);

        // Generate report content based on type
        $html = $this->generatePDFContent($reportType, $locationId, $dateFrom, $dateTo);

        // Write HTML
        $pdf->writeHTML($html, true, false, true, false, '');

        // Output PDF
        $filename = $reportType . '_report_' . date('Ymd') . '.pdf';
        $pdf->Output($filename, 'D'); // D = download
    }

    /**
     * Generate PDF content
     */
    private function generatePDFContent($reportType, $locationId, $dateFrom, $dateTo) {
        require_once __DIR__ . '/../helpers/settings_loader.php';
        $BUSINESS = loadBusinessSettings();

        $html = '<h1>' . e($BUSINESS['business_name']) . '</h1>';
        $html .= '<h2>' . ucfirst($reportType) . ' Report</h2>';
        $html .= '<p>Period: ' . date('d M Y', strtotime($dateFrom)) . ' to ' . date('d M Y', strtotime($dateTo)) . '</p>';
        $html .= '<hr>';

        switch ($reportType) {
            case 'sales':
                $salesData = $this->reportModel->getSalesReport($locationId, $dateFrom, $dateTo);
                $summary = $this->reportModel->getSalesSummary($locationId, $dateFrom, $dateTo);

                $html .= '<h3>Summary</h3>';
                $html .= '<table border="1" cellpadding="5">';
                $html .= '<tr><td><strong>Total Transactions:</strong></td><td>' . ($summary['total_transactions'] ?? 0) . '</td></tr>';
                $html .= '<tr><td><strong>Total Revenue:</strong></td><td>' . formatCurrency($summary['total_revenue'] ?? 0) . '</td></tr>';
                $html .= '<tr><td><strong>Average Transaction:</strong></td><td>' . formatCurrency($summary['avg_transaction'] ?? 0) . '</td></tr>';
                $html .= '</table>';

                $html .= '<h3>Daily Breakdown</h3>';
                $html .= '<table border="1" cellpadding="5">';
                $html .= '<tr><th>Date</th><th>Transactions</th><th>Revenue</th></tr>';
                foreach ($salesData as $row) {
                    $html .= '<tr>';
                    $html .= '<td>' . date('d M Y', strtotime($row['date'])) . '</td>';
                    $html .= '<td>' . $row['transaction_count'] . '</td>';
                    $html .= '<td>' . formatCurrency($row['total_sales']) . '</td>';
                    $html .= '</tr>';
                }
                $html .= '</table>';
                break;

            case 'barbers':
                $barberData = $this->reportModel->getBarberPerformance(0, $dateFrom, $dateTo, $locationId);

                $html .= '<table border="1" cellpadding="5">';
                $html .= '<tr><th>Barber</th><th>Services</th><th>Revenue</th><th>Commission</th></tr>';
                foreach ($barberData as $row) {
                    $html .= '<tr>';
                    $html .= '<td>' . e($row['full_name']) . '</td>';
                    $html .= '<td>' . ($row['service_count'] ?? 0) . '</td>';
                    $html .= '<td>' . formatCurrency($row['total_revenue'] ?? 0) . '</td>';
                    $html .= '<td>' . formatCurrency($row['total_commission'] ?? 0) . '</td>';
                    $html .= '</tr>';
                }
                $html .= '</table>';
                break;
        }

        return $html;
    }
}
