<?php

namespace App\Http\Controllers;
use App\Models\Baseline;
use App\Models\PostLevel;
use App\Models\PreWorkLevel;
use App\Models\QuantityCalculation;
use App\Models\BillApproval;
use App\Models\AssetHandover;
use App\Models\MeasurementBook;
use ZipArchive;
use App\Models\User;
use Illuminate\Support\Facades\Auth;


use Illuminate\Support\Facades\File;


use App\Models\WaterHarvestingStructuresPlanning;


use Illuminate\Http\Request;
use PDF; // Make sure PDF is installed via barryvdh/laravel-dompdf

class PdfController extends Controller
{
    public function baselinePDF($id)
    {
       
         $baseline = Baseline::with([
            'households',
            'lands',
            'livestocks',
            'waterUserGroups',
            'technicalFeasibility',
          //'WaterHarvestingStructuresPlanning',
            'croppings',
            'alliedsectors',
            'microEnterprises',
            'dailyWageLabors',
            'sourceOfFamilyIncome',
            'documentUpload'
        ])->findOrFail($id);

         $pdf = PDF::loadView('pdf.baseline', ['baseline' => $baseline]);
        return $pdf->download('Baseine.pdf');
    }

   private function buildPreLevelPdf($baseline_id)
{
    $baseline = Baseline::with([
        'preWorkLevels',
        'lands',
        'waterHarvestingStructuresPlannings',
        'state',
        'district',
        'panchayat',
        'village'
    ])->findOrFail($baseline_id);

    return PDF::loadView('pdf.preWorkLevel', [
        'baseline' => $baseline
    ]);
}

public function preLevelWorkPDF($id)
{
    return $this->buildPreLevelWorkPdf($id)
                ->download('Prelevel.pdf');
}



public function generatePDF($baseline_id)
{
    return $this->buildPostLevelPdf($baseline_id)
                ->download('PostLevel_Report_' . $baseline_id . '.pdf');
}



private function buildPostLevelPdf($baseline_id)
{
    $postLevel = PostLevel::with([
        'postLevelReadings',
        'baseline.village'
    ])
    ->where('baseline_id', $baseline_id)
    ->firstOrFail();

    $baseline = Baseline::with('lands')->findOrFail($baseline_id);

    $readingsByLayer = $postLevel->postLevelReadings->groupBy('layer_number');
    $preWorkLevel = PreWorkLevel::where('baseline_id', $baseline_id)->first();

    $picture = $preWorkLevel?->picture;

    $averageRl = null;
    if ($preWorkLevel && is_array($preWorkLevel->stations)) {
        $rlValues = collect($preWorkLevel->stations)
            ->pluck('rl')
            ->map(fn ($value) => (float) $value);

        $averageRl = $rlValues->avg();
    }

    return PDF::loadView(
        'pdf.PostLevePdf',
        compact('postLevel', 'readingsByLayer', 'averageRl', 'baseline', 'picture')
    );
}






private function buildQuantityCalculationPdf($id)
{
    $record = QuantityCalculation::with([
        'baseline.preWorkLevels',
        'baseline.postLevel',
        'waterHarvestingStructuresPlanning',
        'land'
    ])->where('baseline_id', $id)->firstOrFail();

    // Location hierarchy
    $villageName   = optional($record->baseline->village)->name ?? '-';
    $panchayatName = optional($record->baseline->village->panchayat)->name ?? '-';
    $blockName     = optional($record->baseline->village->panchayat->block)->name ?? '-';
    $districtName  = optional($record->baseline->village->panchayat->block->district)->name ?? '-';

    $bunds = $record->measurements_for_bund;

    // Aggregations
    $total_length = $total_width = $total_height = $total_slant_length = $total_dressing_area = 0;
    $count = is_array($bunds) ? count($bunds) : 0;

    if ($count > 0) {
        foreach ($bunds as $bund) {
            $total_length        += (float) ($bund['avg_length'] ?? 0);
            $total_width         += (float) ($bund['avg_bottom_width'] ?? 0);
            $total_height        += (float) ($bund['avg_height'] ?? 0);
            $total_slant_length  += (float) ($bund['slant_length'] ?? 0);
            $total_dressing_area += (float) ($bund['dressing_area'] ?? 0);
        }
    }

    $avg_length        = $count ? round($total_length / $count, 3) : null;
    $avg_width         = $count ? round($total_width / $count, 3) : null;
    $avg_height        = $count ? round($total_height / $count, 3) : null;
    $avg_slant_length  = $count ? round($total_slant_length / $count, 3) : null;
    $avg_dressing_area = $count ? round($total_dressing_area, 3) : null;

    $prev_avg_length        = $record->avg_length;
    $prev_avg_width         = $record->avg_width;
    $prev_avg_height        = $record->avg_height;
    $prev_avg_slant_length  = $record->avg_slant_length;
    $prev_avg_dressing_area = $record->avg_dressing_area;

    $estimated_dressing_area   = $record->estimated_dressing_area;
    $payable_dressing_quantity = $record->payable_dressing_quantity;
    $remarks                   = $record->remarks;

    $outletWork              = $record->outlet_work;
    $excavationForSiltTrap   = $record->excavation_for_silt_trap;

    $excavation_for_inlet_obj = is_string($record->excavation_for_inlet)
        ? json_decode($record->excavation_for_inlet)
        : (is_array($record->excavation_for_inlet)
            ? json_decode(json_encode($record->excavation_for_inlet))
            : null);

    $stone_pitching_at_inlet_obj = is_string($record->stone_pitching_at_inlet)
        ? json_decode($record->stone_pitching_at_inlet)
        : (is_array($record->stone_pitching_at_inlet)
            ? json_decode(json_encode($record->stone_pitching_at_inlet))
            : null);

    $display_board_work_data = $record->display_board_work;
    $display_board_work_obj = is_string($display_board_work_data)
        ? json_decode($display_board_work_data, true)
        : (is_array($display_board_work_data) ? $display_board_work_data : []);

    $data['display_board'] = $display_board_work_obj;

    return PDF::loadView(
        'pdf.quantityCalculationPdf',
        compact(
            'villageName',
            'panchayatName',
            'blockName',
            'districtName',
            'record',
            'bunds',
            'avg_length',
            'avg_width',
            'avg_height',
            'avg_slant_length',
            'avg_dressing_area',
            'estimated_dressing_area',
            'payable_dressing_quantity',
            'remarks',
            'prev_avg_length',
            'prev_avg_width',
            'prev_avg_height',
            'prev_avg_slant_length',
            'prev_avg_dressing_area',
            'outletWork',
            'excavationForSiltTrap',
            'excavation_for_inlet_obj',
            'stone_pitching_at_inlet_obj',
            'data'
        )
    );
}

public function quantiteCalculationPDF($id)
{
    return $this->buildQuantityCalculationPdf($id)
                ->download('quantity-calculation-report.pdf');
}



private function buildBillApprovalPdf($id)
{
    $bill = BillApproval::with([
        'baseline.project.pia',
        'baseline.village',
        'baseline.panchayat',
        'baseline.block',
        'baseline.district',
        'baseline.lands'
    ])->where('baseline_id', $id)->firstOrFail();

    $baseline = $bill->baseline;
    $readings = $bill->items;
    $measurementBook = $bill->measurementBook;

    return PDF::loadView('pdf.billapprovalalPdf', compact(
        'bill', 
        'baseline', 
        'readings', 
        'measurementBook'
    ));
}

public function billapprovalPdf($id)
{
    return $this->buildBillApprovalPdf($id)
                ->download('billapproval_' . $id . '.pdf');
}


public function assetHandOver($id)
{
    $assethandovers = AssetHandover::with([
        'unit', 'state', 'district', 'block', 'panchayat', 'village'
    ])->where('baseline_id', $id)->firstOrFail();

    $pdf = Pdf::loadView('pdf.assetHandOver', compact('assethandovers'))
             ->setPaper('a4', 'portrait');

    return $pdf->download('Asset_Handover_Report_' . $assethandovers->baseline_id . '.pdf');
}






private function buildMeasurementBookPdf($id)
{
    $mb = MeasurementBook::with([
        'baseline.village',
        'baseline.panchayat',
        'baseline.block',
        'baseline.district',
        'readings'
    ])->findOrFail($id);

    return PDF::loadView('pdf.measurementbook', compact('mb'));
}

public function measurementook($id)
{
    return $this->buildMeasurementBookPdf($id)
                ->download('measurementbookPdf_' . $id . '.pdf');
}

public function downloadAll()
{
$user_id = auth()->user()->id;

// get child user ids
$child_user_ids = User::where('user_id', $user_id)
    ->pluck('id');

// merge parent + children
$all_user_ids = $child_user_ids
    ->push($user_id)
    ->unique()
    ->values();

// get baseline ids for all those users
$baseline_ids = Baseline::whereIn('user_id', $all_user_ids)
    ->pluck('id');

// get verified bills for those baselines
$approvedBill = BillApproval::where('verification_status', 'verified')
    ->whereIn('baseline_id', $baseline_ids)
    ->get();

    return view('pdf.downloadAllPDF', compact('approvedBill'));
}



public function downloadAllPDF($baseline_id)
{
    $tempPath = storage_path('app/temp_pdfs');

    if (!file_exists($tempPath)) {
        mkdir($tempPath, 0755, true);
    }

    // Pre-Level
    $this->buildPreLevelPdf($baseline_id)
         ->save($tempPath.'/Prelevel.pdf');

    // Post-Level
    $this->buildPostLevelPdf($baseline_id)
         ->save($tempPath.'/PostLevel.pdf');

    // Quantity Calculation
    $this->buildQuantityCalculationPdf($baseline_id)
         ->save($tempPath.'/Quantity_Calculation.pdf');

    // Measurement Book
    $this->buildMeasurementBookPdf($baseline_id)
         ->save($tempPath.'/MeasurementBook.pdf');

    // Bill Approval
    $this->buildBillApprovalPdf($baseline_id)
         ->save($tempPath.'/BillApproval.pdf');

    // Create ZIP
    $zip = new \ZipArchive;
    $zipPath = storage_path('app/All_PDFs_'.$baseline_id.'.zip');

    $zip->open($zipPath, \ZipArchive::CREATE | \ZipArchive::OVERWRITE);
    $zip->addFile($tempPath.'/Prelevel.pdf', 'Prelevel.pdf');
    $zip->addFile($tempPath.'/PostLevel.pdf', 'PostLevel.pdf');
    $zip->addFile($tempPath.'/Quantity_Calculation.pdf', 'Quantity_Calculation.pdf');
    $zip->addFile($tempPath.'/MeasurementBook.pdf', 'MeasurementBook.pdf');
    $zip->addFile($tempPath.'/BillApproval.pdf', 'BillApproval.pdf');
    $zip->close();

    // Cleanup
    \File::deleteDirectory($tempPath);

    return response()->download($zipPath)->deleteFileAfterSend(true);
}


}
