<?php

namespace App\Http\Controllers\CashManage;

use App\Http\Controllers\Controller;
use App\Models\ExpensesCategory;
use App\Models\ExpensesSubCategory;
use App\Models\Expenses_images;
use App\Models\Expenses;
use App\Models\Branches;
use App\Models\pettyCash;
use App\Models\ToDoList;
use App\Models\PurchaseItems;

use Illuminate\Http\Request;

class expensesController extends Controller
{
    public function addExpensesPage()
    {   
        $branches = Branches::get(); 
        $ToDoList = ToDoList::get();
        $ExpensesCategories = ExpensesCategory::get();
        return view('Section.Expenses.adExpenses',compact('ExpensesCategories','branches','ToDoList'));
      
    }

    public function DeleteRequestedExpenses()
    {   
        $Expenses = Expenses::sum('amount');
        $pettyCash= pettyCash::sum('amount');
        $ToDoList = ToDoList::get();
        return view('Section.AdvanceFeatures.DeleteRequestedExpenses',compact('Expenses','pettyCash','ToDoList'));
      
    }

    

    
    public function listExpensesPage()
    {     
        $Expenses = Expenses::sum('amount');
        $pettyCash= pettyCash::sum('amount');
        $ToDoList = ToDoList::get();
        return view('Section.Expenses.expensesList',compact('ToDoList','Expenses','pettyCash'));
      
    }
    public function getExpensesSubCategory(Request $request)
    {
        $data = $request->all();
        $id =$data['id'];
       
        $expensesCategory = ExpensesSubCategory::leftJoin('expenses_categories','expenses_sub_categories.expenses_category_id','=','expenses_categories.id')
        ->select('expenses_sub_categories.*','expenses_categories.expenses_category')->where('expenses_sub_categories.expenses_category_id',$id)->get();
        
        return response()->json(['data' => $expensesCategory]);
    }
    public function storeExpenses(Request $request)
    {
        $data = $request->all();
        // dd($data);

        $expenses = expenses::create([
            'date' =>  $data['date'],    
            'time' =>  $data['time'],
            'expenses' =>  $data['title'],
            'Payment_method' =>  $data['PaymentMethods'],
            'amount' =>  $data['amount'],
            'branches_id'=>  $data['branchId'],
            'delete_permission'=> 0,
            'sub_expenses_category_id' =>  $data['subCategory'],  
            'expenses_category_id' =>  $data['Category'],   
            'description' =>  $data['description'],   
        ]);

        $mortgageData = isset($data['mortgageData']) ? $data['mortgageData'] : [];

        foreach ($mortgageData as $rowData) {    
            $PurchaseItems = PurchaseItems::create([
                'item_name' => $rowData['item'],
                'item_quantity' => $rowData['quantity'],
                'price' => str_replace(',', '', $rowData['itemPrice']), // Remove commas from itemPrice
                'expenses_id' => $expenses->id,
            ]);
        }
    
        if ($request->hasFile('expensesImages')) {
            foreach ($request->file('expensesImages') as $index => $image) {
                $imageName = time() . rand(1, 9) . '.' . $image->getClientOriginalExtension();
                $image->move('assets/Expenses', $imageName);

                $Expenses_images = new Expenses_images();
                $Expenses_images->image_name = $imageName;
                $Expenses_images->expenses_id = $expenses->id;
                $Expenses_images->save();
            }
        }
        if($expenses){
            return response()->json([
                'status' => 'success',
                'message' => 'success'
            ]);
        }
       
    }
    

    public function listExpenses()
    {
        
     $ExpensesCategory = Expenses::leftJoin('expenses_sub_categories','expenses.sub_expenses_category_id','=','expenses_sub_categories.id')
     ->leftJoin('expenses_categories','expenses.expenses_category_id','=','expenses_categories.id')
     ->select('expenses.*','expenses_sub_categories.expenses_sub_category','expenses_categories.expenses_category')->get();
  
        $response['data'] = $ExpensesCategory;
        return response()->json($response);

    }


    public function DeleteRequestedlistExpenses()
    {
        
     $ExpensesCategory = Expenses::leftJoin('expenses_sub_categories','expenses.sub_expenses_category_id','=','expenses_sub_categories.id')
     ->leftJoin('expenses_categories','expenses_sub_categories.expenses_category_id','=','expenses_categories.id')
     ->select('expenses.*','expenses_sub_categories.expenses_sub_category','expenses_categories.expenses_category')
     ->where('expenses.delete_permission', 1)->get();
  
        $response['data'] = $ExpensesCategory;
        return response()->json($response);

    }

    

    
    public function deleteExpenses(Request $request)
    {
        $data = $request->all();
        $id = $data['id'];
        $Expenses = Expenses::find($id);
        if (!$Expenses) {
            return response()->json(['message' => 'Staff member not found'], 404);
        }

        $Expenses->delete();

        return response()->json(['message' => 'Staff member deleted'], 200);

    
    }

    public function RequestdeleteExpenses(Request $request)
    {
        $data = $request->all();
        $id = $data['id'];
        $delete_reason = $data['DeleteReason'];
        $Expenses = Expenses::find($id);
    
        if (!$Expenses) {
            return response()->json(['message' => 'Expense not found'], 404);
        }
    
        $Expenses->update([
            'delete_permission' => 1,
            'delete_reason' => $delete_reason,
        ]);

    
        return response()->json(['message' => 'Expense delete permission updated'], 200);
    }


    public function AcceptRequestdeleteExpenses(Request $request)
    {
        $data = $request->all();
        $id = $data['id'];
        $Expenses = Expenses::find($id);
    
        if (!$Expenses) {
            return response()->json(['message' => 'Expense not found'], 404);
        }
    
        $Expenses->update([
            'delete_permission' => 2,
        ]);

    
        return response()->json(['message' => 'Expense delete permission updated'], 200);
    }

    

    

    public function listExpensesData(Request $request)
    {

        $ToDoList = ToDoList::get();
        $id = $request->input('id');

        $ExpensesData = Expenses::leftJoin('expenses_sub_categories', 'expenses.sub_expenses_category_id', '=', 'expenses_sub_categories.id')
        ->leftJoin('expenses_categories', 'expenses_sub_categories.expenses_category_id', '=', 'expenses_categories.id')
        ->leftJoin('branches', 'expenses.branches_id', '=', 'branches.id')
        ->select('expenses.*','branches.branch_name', 'expenses_sub_categories.expenses_sub_category', 'expenses_categories.expenses_category')
        ->where('expenses.id', $id)
        ->first();

    if ($ExpensesData) {
        $Expenses_images = Expenses_images::where('expenses_id', $ExpensesData->id)->get();
        $ExpensesData->Expenses_images = $Expenses_images;
    }

    if ($ExpensesData) {
        $PurchaseItems = PurchaseItems::where('expenses_id', $ExpensesData->id)->get();
        $ExpensesData->PurchaseItems = $PurchaseItems;
    }



        return view('Section.Expenses.expensesData',compact('ExpensesData','ToDoList'));

    }


    public function updateExpensesData(Request $request)
    {
        $ToDoList = ToDoList::get();
        $branches = Branches::get(); 
        $ExpensesCategories = ExpensesCategory::get();
        $ExpensesSubCategories = ExpensesSubCategory::get();
        $id = $request->input('id');
    $ExpensesData = Expenses::leftJoin('expenses_sub_categories', 'expenses.sub_expenses_category_id', '=', 'expenses_sub_categories.id')
        ->leftJoin('expenses_categories', 'expenses_sub_categories.expenses_category_id', '=', 'expenses_categories.id')
        ->leftJoin('branches', 'expenses.branches_id', '=', 'branches.id')
        ->select('expenses.*','branches.branch_name', 'expenses_sub_categories.expenses_sub_category', 'expenses_categories.expenses_category')
        ->where('expenses.id', $id)
        ->first();

    if ($ExpensesData) {
        $Expenses_images = Expenses_images::where('expenses_id', $ExpensesData->id)->get();
        $ExpensesData->Expenses_images = $Expenses_images;
    }

    if ($ExpensesData) {
        $PurchaseItems = PurchaseItems::where('expenses_id', $ExpensesData->id)->get();
        $ExpensesData->PurchaseItems = $PurchaseItems;
    }


        return view('Section.Expenses.editExpensesData',compact('ExpensesData','branches','ExpensesCategories','ExpensesSubCategories','ToDoList'));

    }
   
    
    
    public function updateExpenses(Request $request)
    {
        $data = $request->all();
        $expenses_id = $data['expenses_id'];
    
        // Retrieve the existing expense record
        $expense = Expenses::find($expenses_id);
    
        if ($expense) {
            // Update the expense record
            $expense->update([
                'date' =>  $data['date'],    
                'time' =>  $data['time'],
                'expenses' =>  $data['title'],
                'amount' =>  str_replace(',', '', $data['amount']), // Remove commas from amount
                'branches_id'=>  $data['branchId'],
                'sub_expenses_category_id' =>  $data['subCategory'],    
                'description' =>  $data['description'],
            ]);
    
            // Array to keep track of updated purchase item IDs
            $updatedItemIds = [];


            $mortgageData = isset($data['mortgageData']) ? $data['mortgageData'] : [];
    
            // Update or create purchase items
            foreach ($mortgageData as $rowData) {
                $rowData['itemPrice'] = str_replace(',', '', $rowData['itemPrice']); // Remove commas from itemPrice
    
                if (isset($rowData['id'])) {
                    // Find the purchase item by ID and update it
                    $purchaseItem = PurchaseItems::find($rowData['id']);
                    if ($purchaseItem) {
                        $purchaseItem->update([
                            'item_name' => $rowData['item'],
                            'item_quantity' => $rowData['quantity'],
                            'price' => $rowData['itemPrice'],
                        ]);
                        $updatedItemIds[] = $purchaseItem->id;
                    }
                } else {
                    // Create a new purchase item
                    $newItem = PurchaseItems::create([
                        'item_name' => $rowData['item'],
                        'item_quantity' => $rowData['quantity'],
                        'price' => $rowData['itemPrice'],
                        'expenses_id' => $expenses_id,
                    ]);
                    $updatedItemIds[] = $newItem->id;
                }
            }
            if ($request->hasFile('expensesImages')) {
                foreach ($request->file('expensesImages') as $index => $image) {
                    $imageName = time() . rand(1, 9) . '.' . $image->getClientOriginalExtension();
                    $image->move('assets/Expenses', $imageName);
    
                    $Expenses_images = new Expenses_images();
                    $Expenses_images->image_name = $imageName;
                    $Expenses_images->expenses_id = $expense->id;
                    $Expenses_images->save();
                }
            }
    
            // Delete purchase items that were not included in the update
            PurchaseItems::where('expenses_id', $expenses_id)
                          ->whereNotIn('id', $updatedItemIds)
                          ->delete();
    
            return response()->json(['message' => 'Expense updated successfully'], 200);
        } else {
            return response()->json(['message' => 'Expense not found'], 404);
        }
    }
    
    public function deleteImages(Request $request)
    {
        $data = $request->all();
        $expenses_id = $data['id'];
    
        // Retrieve the existing expense record
        $Expenses_images = Expenses_images::find($expenses_id);
        $delete = $Expenses_images->delete();

        if($delete ){
            return response()->json(['message' => 'Expense updated successfully'], 200);
    } else {
        return response()->json(['message' => 'Expense not found'], 404);
    }
    
    }
    
}


