<?php
class BatchController {
    public function index(): void {
        Auth::requireLogin();
        Auth::requireActiveTenant();
        Auth::requirePermission('stock.view');

        $tid = Auth::tenantId();
        $page = (int)($_GET['page'] ?? 1) ?: 1;
        $perPage = $_GET['per_page'] ?? ITEMS_PER_PAGE;
        $pp = $perPage === 'all' ? PHP_INT_MAX : (int)$perPage;
        $offset = ($page - 1) * $pp;

        // Get total count
        $cntStmt = db()->prepare("SELECT COUNT(*) FROM batches WHERE tenant_id = ?");
        $cntStmt->execute([$tid]);
        $total = (int)$cntStmt->fetchColumn();

        // Get paginated batches with product and location info
        $stmt = db()->prepare("
            SELECT b.*, p.name as product_name, l.name as location_name
            FROM batches b
            LEFT JOIN products p ON b.product_id = p.id
            LEFT JOIN locations l ON b.location_id = l.id
            WHERE b.tenant_id = ? 
            ORDER BY b.mfg_date DESC, b.batch_no DESC
            LIMIT {$pp} OFFSET {$offset}
        ");
        $stmt->execute([$tid]);
        $batches = [
            'data' => $stmt->fetchAll(),
            'total' => $total,
            'last_page' => $perPage === 'all' ? 1 : (int)ceil($total / $pp),
            'page' => $page
        ];

        $pageTitle = 'Batch Management';
        ob_start();
        include APP_ROOT . '/views/tenant/batches/index.php';
        $content = ob_get_clean();
        include APP_ROOT . '/views/tenant/layouts/main.php';
    }

    public function create(): void {
        Auth::requireLogin();
        Auth::requireActiveTenant();
        Auth::requirePermission('stock.view');
        Security::checkCsrf();

        $tid = Auth::tenantId();
        $productId = (int)($_POST['product_id'] ?? 0);
        $locationId = (int)($_POST['location_id'] ?? null);
        $batchNo = trim($_POST['batch_no'] ?? '');
        $mfgDate = $_POST['mfg_date'] ?? '';
        $expiryDate = $_POST['expiry_date'] ?? '';
        $quantity = (float)($_POST['quantity'] ?? 0);

        // Validate inputs
        if (empty($productId)) {
            flash('error', 'Product is required');
            redirect('products/create');
            return;
        }

        if (empty($batchNo)) {
            flash('error', 'Batch number is required');
            redirect('products/create');
            return;
        }

        if (empty($mfgDate)) {
            flash('error', 'Manufacturing date is required');
            redirect('products/create');
            return;
        }

        if ($quantity <= 0) {
            flash('error', 'Quantity must be greater than 0');
            redirect('products/create');
            return;
        }

        try {
            $stmt = db()->prepare("
                INSERT INTO batches (tenant_id, product_id, location_id, batch_no, mfg_date, expiry_date, quantity)
                VALUES (?, ?, ?, ?, ?, ?, ?)
            ");
            $stmt->execute([$tid, $productId, $locationId, $batchNo, $mfgDate, $expiryDate, $quantity]);
            
            flash('success', 'Batch created successfully');
        } catch (Exception $e) {
            flash('error', 'Failed to create batch: ' . $e->getMessage());
        }

        redirect('products/create');
    }

    public function edit(int $id): void {
        Auth::requireLogin();
        Auth::requireActiveTenant();
        Auth::requirePermission('stock.view');

        $tid = Auth::tenantId();
        
        $stmt = db()->prepare("
            SELECT b.*, p.name as product_name, l.name as location_name
            FROM batches b
            LEFT JOIN products p ON b.product_id = p.id
            LEFT JOIN locations l ON b.location_id = l.id
            WHERE b.id = ? AND b.tenant_id = ?
        ");
        $stmt->execute([$id, $tid]);
        $batch = $stmt->fetch();

        if (!$batch) {
            flash('error', 'Batch not found');
            redirect('batches');
            return;
        }

        $pageTitle = 'Edit Batch';
        ob_start();
        include APP_ROOT . '/views/tenant/batches/edit.php';
        $content = ob_get_clean();
        include APP_ROOT . '/views/tenant/layouts/main.php';
    }

    public function update(): void {
        Auth::requireLogin();
        Auth::requireActiveTenant();
        Auth::requirePermission('stock.view');
        Security::checkCsrf();

        $tid = Auth::tenantId();
        $id = (int)($_POST['id'] ?? 0);
        $locationId = (int)($_POST['location_id'] ?? null);
        $batchNo = trim($_POST['batch_no'] ?? '');
        $mfgDate = $_POST['mfg_date'] ?? '';
        $expiryDate = $_POST['expiry_date'] ?? '';
        $quantity = (float)($_POST['quantity'] ?? 0);

        // Validate inputs
        if (empty($batchNo)) {
            flash('error', 'Batch number is required');
            redirect("batches/edit/{$id}");
            return;
        }

        if (empty($mfgDate)) {
            flash('error', 'Manufacturing date is required');
            redirect("batches/edit/{$id}");
            return;
        }

        if ($quantity <= 0) {
            flash('error', 'Quantity must be greater than 0');
            redirect("batches/edit/{$id}");
            return;
        }

        try {
            $stmt = db()->prepare("
                UPDATE batches 
                SET location_id = ?, batch_no = ?, mfg_date = ?, expiry_date = ?, quantity = ?
                WHERE id = ? AND tenant_id = ?
            ");
            $stmt->execute([$locationId, $batchNo, $mfgDate, $expiryDate, $quantity, $id, $tid]);
            
            flash('success', 'Batch updated successfully');
        } catch (Exception $e) {
            flash('error', 'Failed to update batch: ' . $e->getMessage());
        }

        redirect('batches');
    }

    public function delete(): void {
        Auth::requireLogin();
        Auth::requireActiveTenant();
        Auth::requireRole(['admin','owner']);
        Security::checkCsrf();

        $tid = Auth::tenantId();
        $id = (int)($_POST['id'] ?? 0);

        try {
            // Check if batch has stock entries
            $stmt = db()->prepare("SELECT COUNT(*) FROM stock WHERE batch_id = ? AND tenant_id = ?");
            $stmt->execute([$id, $tid]);
            $stockCount = $stmt->fetchColumn();

            if ($stockCount > 0) {
                flash('error', 'Cannot delete batch with existing stock entries');
                redirect('batches');
                return;
            }

            // Delete the batch
            $stmt = db()->prepare("DELETE FROM batches WHERE id = ? AND tenant_id = ?");
            $stmt->execute([$id, $tid]);
            
            flash('success', 'Batch deleted successfully');
        } catch (Exception $e) {
            flash('error', 'Failed to delete batch: ' . $e->getMessage());
        }

        redirect('batches');
    }

    public function getBatches(int $productId): array {
        $tid = Auth::tenantId();
        
        $stmt = db()->prepare("
            SELECT b.*, l.name as location_name
            FROM batches b
            LEFT JOIN locations l ON b.location_id = l.id
            WHERE b.product_id = ? AND b.tenant_id = ?
            ORDER BY b.mfg_date DESC, b.batch_no DESC
        ");
        $stmt->execute([$productId, $tid]);
        return $stmt->fetchAll();
    }
}
