<?php

namespace App\Http\Controllers\admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Order;
use Carbon\Carbon;
use Illuminate\Support\Facades\Response;

class TaxReportController extends Controller
{
    public function index(Request $request)
    {
        $startDate = $request->input('start_date');
        $endDate = $request->input('end_date');
        $taxBase = \App\Models\SystemSetting::get('tax_calculation_base', 'selling_price');
        $taxRate = (float) \App\Models\SystemSetting::get('corporate_tax_percentage', 18.00);

        $query = Order::where(function ($q) {
            $q->whereNull('cancellation')->orWhere('cancellation', 0);
        })->whereNotNull('tax_amount')->where('tax_amount', '>', 0)->latest();

        if ($startDate && $endDate) {
            $query->whereBetween('created_at', [
                Carbon::parse($startDate)->startOfDay(),
                Carbon::parse($endDate)->endOfDay()
            ]);
        }

        // Get orders that have non-zero tax, eager load user and product relation
        $taxableOrders = $query->with(['user', 'productData'])->get();
        
        // Calculate totals on the collection for display
        $totalRevenue = 0;
        $totalTax = 0;
        $totalCollectedTax = 0;

        foreach ($taxableOrders as $order) {
            $totalRevenue += $order->total;
            $totalCollectedTax += $order->tax_amount;
            
            // Re-calculate based on current setting for the report view
            $product = $order->productData;
            if ($product) {
                $basePrice = ($taxBase === 'cutted_price' && $product->cutted_price) ? $product->cutted_price : ($order->total / max(1, $order->quantity));
                $calculatedTax = round(($basePrice * $order->quantity * $taxRate) / 100, 2);
                $order->calculated_tax = $calculatedTax;
            } else {
                $order->calculated_tax = $order->tax_amount;
            }
            
            $totalTax += $order->calculated_tax;
        }

        return view('admin.reports.tax_report', compact('taxableOrders', 'totalRevenue', 'totalTax', 'totalCollectedTax', 'startDate', 'endDate', 'taxBase', 'taxRate'));
    }

    public function updateTaxBase(Request $request)
    {
        $request->validate([
            'tax_calculation_base' => 'required|in:selling_price,cutted_price'
        ]);

        \App\Models\SystemSetting::set('tax_calculation_base', $request->tax_calculation_base);

        return back()->with('success', 'Tax calculation base updated to ' . ($request->tax_calculation_base === 'selling_price' ? 'Selling Price' : 'Cutted Price'));
    }

    public function updateTaxRate(Request $request)
    {
        $request->validate([
            'corporate_tax_percentage' => 'required|numeric|min:0|max:100'
        ]);

        \App\Models\SystemSetting::set('corporate_tax_percentage', $request->corporate_tax_percentage);

        return back()->with('success', 'Corporate tax percentage updated to ' . $request->corporate_tax_percentage . '%');
    }

    public function download(Request $request)
    {
         $startDate = $request->input('start_date');
        $endDate = $request->input('end_date');
        $taxBase = \App\Models\SystemSetting::get('tax_calculation_base', 'selling_price');
        $taxRate = (float) \App\Models\SystemSetting::get('corporate_tax_percentage', 18.00);

        $query = Order::where(function ($q) {
            $q->whereNull('cancellation')->orWhere('cancellation', 0);
        })->whereNotNull('tax_amount')->where('tax_amount', '>', 0)->latest();

        if ($startDate && $endDate) {
            $query->whereBetween('created_at', [
                Carbon::parse($startDate)->startOfDay(),
                Carbon::parse($endDate)->endOfDay()
            ]);
        }

        $taxableOrders = $query->with(['user', 'productData'])->get();

        foreach ($taxableOrders as $order) {
            $product = $order->productData;
            if ($product) {
                $basePrice = ($taxBase === 'cutted_price' && $product->cutted_price) ? $product->cutted_price : ($order->total / max(1, $order->quantity));
                $order->calculated_tax = round(($basePrice * $order->quantity * $taxRate) / 100, 2);
            } else {
                $order->calculated_tax = $order->tax_amount;
            }
        }

        $headers = [
            "Content-type"        => "text/csv",
            "Content-Disposition" => "attachment; filename=tax_report_" . date('Y-m-d') . ".csv",
            "Pragma"              => "no-cache",
            "Cache-Control"       => "must-revalidate, post-check=0, pre-check=0",
            "Expires"             => "0"
        ];

        $callback = function() use($taxableOrders) {
            $file = fopen('php://output', 'w');
            
            // Header row
            fputcsv($file, ['Order ID', 'Date', 'Customer Name', 'Email', 'Order Total (LKR)', 'Collected Tax (LKR)', 'Calculated Tax (LKR)']);

            foreach ($taxableOrders as $order) {
                fputcsv($file, [
                    $order->order_id,
                    $order->created_at->format('Y-m-d H:i'),
                    $order->user ? $order->user->name : 'Guest',
                    $order->user ? $order->user->email : '-',
                    number_format($order->total, 2, '.', ''),
                    number_format($order->tax_amount, 2, '.', ''),
                    number_format($order->calculated_tax, 2, '.', '')
                ]);
            }
            
            fclose($file);
        };

        return Response::stream($callback, 200, $headers);
    }
}
