<?php

namespace App\Controllers;

use App\Utils\Auth;
use App\Config\Database;

class ExpiryCheckController {
    
    public function index() {
        Auth::requireLogin();
        
        if (!Auth::hasPrivilege('expiry_check')) {
            header("Location: /dashboard");
            exit;
        }
        
        $user = Auth::user();
        $db = Database::getInstance()->getConnection();
        
        $branches = [];
        $selectedBranch = $_GET['branch_id'] ?? 'all';
        
        if ($user['role'] === 'admin') {
            $stmt = $db->prepare("SELECT id, name FROM branches WHERE tenant_id = ? ORDER BY name ASC");
            $stmt->execute([$user['tenant_id']]);
            $branches = $stmt->fetchAll();
        } else {
            $selectedBranch = $user['branch_id'];
        }

        // Fetch Branch Name
        if ($selectedBranch === 'all') {
            $branchName = 'All Branches';
        } else {
            $stmt = $db->prepare("SELECT name FROM branches WHERE id = ?");
            $stmt->execute([$selectedBranch]);
            $branchName = $stmt->fetchColumn() ?: 'Global Access';
        }

        // Default selected date: today
        $selectedDate = $_GET['date'] ?? date('Y-m-d');
        
        $branchQuery = "";
        $params = [$user['tenant_id']];
        if ($selectedBranch !== 'all') {
            $branchQuery = " AND ib.branch_id = ?";
            $params[] = $selectedBranch;
        }
        $params[] = $selectedDate;

        // Fetch Aggregated Expiry Data for Chart.js (grouped by date)
        $stmt = $db->prepare("
            SELECT ib.expiry_date, COUNT(*) as batch_count, SUM(ib.quantity) as total_quantity
            FROM inventory_batches ib
            WHERE ib.tenant_id = ? $branchQuery 
              AND ib.status = 'active' 
              AND ib.quantity > 0 
              AND ib.expiry_date <= ?
            GROUP BY ib.expiry_date
            ORDER BY ib.expiry_date ASC
        ");
        $stmt->execute($params);
        $chartData = $stmt->fetchAll();

        // Fetch Detailed Batches
        $stmt = $db->prepare("
            SELECT ib.*, m.name as medicine_name, m.generic_name, b.name as branch_name,
                   DATEDIFF(ib.expiry_date, CURDATE()) as days_left
            FROM inventory_batches ib
            JOIN medicines m ON ib.medicine_id = m.id
            JOIN branches b ON ib.branch_id = b.id
            WHERE ib.tenant_id = ? $branchQuery 
              AND ib.status = 'active' 
              AND ib.quantity > 0 
              AND ib.expiry_date <= ?
            ORDER BY ib.expiry_date ASC, m.name ASC
        ");
        $stmt->execute($params);
        $batches = $stmt->fetchAll();

        require_once __DIR__ . '/../../views/admin/expiry_check.php';
    }

    public function remove() {
        Auth::requireLogin();
        
        if (!Auth::hasPrivilege('expiry_check')) {
            header("Location: /dashboard");
            exit;
        }

        $batchId = $_GET['batch_id'] ?? null;
        if ($batchId) {
            $user = Auth::user();
            $db = Database::getInstance()->getConnection();
            
            // Security check: Only delete if it belongs to this tenant
            $stmt = $db->prepare("DELETE FROM inventory_batches WHERE id = ? AND tenant_id = ?");
            $stmt->execute([$batchId, $user['tenant_id']]);
            
            \App\Utils\Flash::set('success', 'Expired batch removed successfully.');
        }

        header("Location: /expiryCheck");
        exit;
    }
}
