<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Payment;
use App\Models\Project;
use App\Models\ServiceRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;

class ProjectManageController extends Controller
{
    public function index($id)
    {
        $serviceRequest = ServiceRequest::findOrFail($id);
        $services = $serviceRequest->services_data;
        $contactInfo = $serviceRequest->contact_info;


        $services = collect($services)->map(function ($item, $index) {
            unset($item['description']);
            unset($item['price']);
            unset($item['id']);

            $item['status'] = 'Not Started';
            $item['id'] = $index + 1;

            return $item;
        })->toArray();

        return view('admin.project-manage.index', compact('serviceRequest', 'services', 'contactInfo'));
    }





    public function submit_project(Request $request, $id)
    {
        $serviceRequest = ServiceRequest::findOrFail($id);

        $serviceRequest = ServiceRequest::findOrFail($id);
        $services = $serviceRequest->services_data;


        $services = collect($services)->map(function ($item, $index) {
            unset($item['description']);
            unset($item['price']);
            unset($item['id']);

            $item['status'] = 'Not Started';
            $item['id'] = $index + 1;

            return $item;
        })->toArray();

        $document_array = json_decode($request->input('document_array'), true);

        $amout = $serviceRequest->amount;
        $request_id = $serviceRequest->id;
        $amount_paid = 0;
        $nPartialPayments = 0;


        $project = new Project();
        $project->request_id = $request_id;
        $project->name = $request->input('name');
        $project->user_id = $serviceRequest->user_id;
        $project->services = json_encode($services);
        $project->documents_data = json_encode($document_array);
        $project->amount = $amout;
        $project->amount_paid = $amount_paid;
        $project->nPartialPayments = $nPartialPayments;
        $project->status = 'Active';
        $project->branch_id = $serviceRequest->branch_id;
        $project->save();
        return redirect()->route('admin.service-requests.index')->with('success', 'Project started successfully.');
    }




    public function allProject()
    {
        $query = Project::with(['serviceRequest', 'user']);
        if (auth()->user()->role !== 'admin') {
            $query->where('branch_id', auth()->user()->branch_id);
        }
        $projects = $query->latest()->get();
        return view('admin.project-manage.all-project', compact('projects'));
    }



    public function show($id)
    {
        $project = Project::with(['serviceRequest', 'user'])->findOrFail($id);
        $payents = Payment::where('project_id', $id)->get();

        return view('admin.project-manage.show-project', compact('project', 'payents'));
    }
    public function upload_data($id)
    {
        $project = Project::with(['serviceRequest', 'user'])->findOrFail($id);
        return view('admin.project-manage.upload-data', compact('project'));
    }


    public function updateStatus($id, Request $request)
    {
        $project = Project::findOrFail($id);
        $project->status = $request->status;
        $project->save();

        return redirect()->back()->with('success', 'Project status updated successfully.');
    }

    public function updateServiceStatus($id, Request $request)
    {
        $project = Project::findOrFail($id);
        $services = is_array($project->services) ? $project->services : json_decode($project->services, true);

        // Update the specific service status
        $serviceKey = $request->service_key;
        if (isset($services[$serviceKey])) {
            $services[$serviceKey]['status'] = $request->service_status;
            $project->services = $services;
            $project->save();
        }

        return redirect()->back()->with('success', 'Service status updated successfully.');
    }



    public function discount($id, Request $request)
    {
        $project = Project::findOrFail($id);
        $servicesRequest = ServiceRequest::findOrFail($project->request_id);
        $project->discount = $request->discount;
        $project->discount_type = $request->type == 'percentage' ? '%' : 'SR';



        $totalPrice = (float) $servicesRequest->total_price;
        $discount = (float) $request->discount;

        if ($request->type === 'percentage') {
            $discountAmount = $totalPrice * ($discount / 100);

            $servicesRequest->total_price = $totalPrice - $discountAmount;
        } else {
            $servicesRequest->total_price = $totalPrice - $discount;
        }


        $project->save();
        $servicesRequest->save();
        return redirect()->back()->with('success', 'Project discount updated successfully.');
    }



    public function create_payment($id)
    {
        $project = Project::findOrFail($id);
        return view('admin.project-manage.create-payment', compact('project'));
    }



    public function uploadServiceDocument($id)
    {
        $project = Project::with(['serviceRequest', 'user'])->findOrFail($id);

        return view('admin.project-manage.upload-service-document', compact('project'));
    }

   
    public function storeServiceDocument(Request $request, $id)
{
    $project = Project::findOrFail($id);
    
    // Validate request
    $validator = Validator::make($request->all(), [
        'service_id' => 'required|string',
        'document_name' => 'required|string|max:255',
        'document_file' => 'required|file|mimes:pdf,jpg,jpeg,png,doc,docx,xls,xlsx|max:10240',
        'notes' => 'nullable|string|max:500'
    ]);
    
    if ($validator->fails()) {
        return redirect()->back()
            ->withErrors($validator)
            ->withInput();
    }
    
    try {
        // File upload
        $file = $request->file('document_file');
        $originalName = $file->getClientOriginalName();
        $extension = $file->getClientOriginalExtension();
        
        // Generate unique filename
        $fileName = 'project_' . $project->id . '_service_' . $request->service_id . '_' . time() . '.' . $extension;
        
        // Store file
        $filePath = $file->storeAs('project-documents', $fileName, 'public');
        
        // Prepare document data
        $newDocument = [
            'name' => $request->document_name,
            'original_name' => $originalName,
            'file_path' => Storage::url($filePath),
            'file_name' => $fileName,
            'file_size' => $file->getSize(),
            'file_type' => $extension,
            'uploaded_at' => now()->toDateTimeString(),
            'uploaded_by' => auth()->id(),
            'notes' => $request->notes ?? '',
            'status' => 'active'
        ];
        
        // Get existing services
        $services = json_decode($project->services, true) ?? [];
        
        // Find the service and add document
        if (isset($services[$request->service_id])) {
            // Initialize documents array if not exists
            if (!isset($services[$request->service_id]['documents'])) {
                $services[$request->service_id]['documents'] = [];
            }
            
            // Add new document
            $services[$request->service_id]['documents'][] = $newDocument;
            
            // Auto-update service status to "In Progress" if not already
            if ($services[$request->service_id]['status'] === 'Not Started') {
                $services[$request->service_id]['status'] = 'In Progress';
            }
            
            // Update project
            $project->update([
                'services' => json_encode($services)
            ]);
            
            return redirect()->back()->with('success', 'Document uploaded successfully!');
        }
        
        return redirect()->back()
            ->with('error', 'Service not found!')
            ->withInput();
            
    } catch (\Exception $e) {
        return redirect()->back()
            ->with('error', 'Failed to upload document: ' . $e->getMessage())
            ->withInput();
    }
}

public function deleteServiceDocument(Request $request, $id)
{
    $project = Project::findOrFail($id);
    
    $request->validate([
        'service_id' => 'required|string',
        'document_index' => 'required|integer'
    ]);
    
    try {
        $services = json_decode($project->services, true) ?? [];
        
        if (isset($services[$request->service_id])) {
            $service = &$services[$request->service_id];
            
            // Check if documents array exists
            if (isset($service['documents']) && isset($service['documents'][$request->document_index])) {
                $document = $service['documents'][$request->document_index];
                
                // Delete file from storage
                if (isset($document['file_name'])) {
                    Storage::disk('public')->delete('project-documents/' . $document['file_name']);
                }
                
                // Remove document from array
                array_splice($service['documents'], $request->document_index, 1);
                
                // Update project
                $project->update([
                    'services' => json_encode($services)
                ]);
                
                return redirect()->back()->with('success', 'Document deleted successfully!');
            }
        }
        
        return redirect()->back()->with('error', 'Document not found.');
        
    } catch (\Exception $e) {
        return redirect()->back()->with('error', 'Failed to delete document: ' . $e->getMessage());
    }
}
}


