<?php

namespace App\Http\Controllers;

use App\Models\Payment;
use App\Models\Project;
use App\Models\Transaction;
use Illuminate\Http\Request;

class ClientProjectsController extends Controller
{
    public function index()
    {

        $projects = Project::with(['serviceRequest', 'user'])
            ->where('user_id', auth()->id())
            ->get();

        return view('dashboard.projects.index', compact('projects'));
    }



    public function show($id)
    {

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

        return view('dashboard.projects.show', compact('project', 'payents'));
    }




    public function pay($id)
    {
        $invoice = Payment::with('project')
            ->where('id', $id)
            ->orderBy('created_at', 'desc')
            ->firstOrFail();

        return view('dashboard.projects.pay', compact('invoice'));
    }


    public function processPayment(Request $request, $id)
    {
        $request->validate([
            'payment_method' => 'required|string|max:255',
            'payment_date' => 'required|date',
            'transaction_id' => 'required|string|max:255',
        ]);

        $payment = Payment::findOrFail($id);
        $payment->payment_method = $request->payment_method;
        $payment->payment_date = $request->payment_date;
        $payment->transaction_id = $request->transaction_id;
        $payment->status = 'pending';
        $payment->save();


        $user__id = $payment->user_id;
        $project_id = $payment->project_id;


        $transection = new Transaction();
        $transection->project_id = $project_id;
        $transection->user_id = $user__id;
        $transection->payment_method = $request->payment_method;
        $transection->payment_date = $request->payment_date;
        $transection->transaction_id = $request->transaction_id;
        $transection->sender_name = $request->sender_name;
        $transection->sender_account = $request->sender_account;
        $transection->payment_reference = $request->payment_reference;
        $transection->notes = $request->notes;
        $transection->branch_id =$payment->branch_id;
        $transection->status = 'pending_verification';
        if ($request->hasFile('payment_screenshot')) {
            $image_path = $request->file('payment_screenshot')->store('payment_screenshots', 'public');
            $transection->payment_screenshot = asset('storage/' . $image_path);
        }
        $transection->save();
        return redirect()->route('dashboard.project.show', $project_id)->with('success', 'Payment processed successfully.');
    }
}