<?php
namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Query\Builder;

use App\Models\CustomBilling;
use App\Models\Customer;
use App\Models\CustomBillingItem;

class CustomBillingController extends Controller{
    
    public function index(Request $request)
    {
        $billings = CustomBilling::leftJoin('custom_billing_items','custom_billing_items.billing_id','=','custom_billings.id')
            ->leftJoin('customers','customers.id','=','custom_billings.customer_id')
            ->select('custom_billings.id','custom_billings.inv_number','custom_billings.transport','custom_billings.discount','custom_billings.payment_status','custom_billings.termin','custom_billings.duedate_at','custom_billings.created_at','custom_billings.customer_id','customers.name', DB::raw('sum(custom_billing_items.amount) as jumlah'))
            ->groupBy('custom_billings.id','custom_billings.inv_number','custom_billings.transport','custom_billings.discount','custom_billings.payment_status','custom_billings.termin','custom_billings.duedate_at','custom_billings.created_at','custom_billings.customer_id','customers.name')
            ->paginate(15);
        
        if($request->page==''){
            return redirect('custom-billing?page='.$billings->lastPage());
        }else{
            return view('admin/custom-billing',['customers'=>Customer::get(),'billings'=>$billings,'title'=>'AR Custom Invoice']);
        }
    }
    
    public function insert(Request $request){
        date_default_timezone_set("Asia/Jakarta");

        $custId = $request->cust_id;
        $invNumber = $request->inv_number;
        $reference = $request->reference;
        
        $values = array('customer_id'=>$custId,'inv_number'=>$invNumber,'reference'=>$reference);
        $insertedId = CustomBilling::insertGetId($values);
        $values['id'] = $insertedId;
        
        return $values;
    }
    
    /*
    public function create(Request $request){
        return view('admin/billing_create',['billing_id'=>null,'customers'=>Customer::get(),'title'=>'Billing']);
    }
    */
    
    public function delete(Request $request)
    {
        date_default_timezone_set("Asia/Jakarta");
        
        //Delete billing items if exists
        $result = DB::table('custom_billing_items')->where('billing_id',$request->id)->get();
        if($result != null){
            //DB::table('custom_billing_items')->where('billing_id',$request->id)->delete();
            CustomBillingItem::where('billing_id',$request->id)->delete();
        }
        
        //DB::table('custom_billings')->where('id',$request->id)->delete();
        CustomBilling::where('id',$request->id)->delete();
        
        return response()->json(['error'=>false]);
        
    }
    
    /*
    public function approve(Request $request){
        date_default_timezone_set("Asia/Jakarta");
        $values = array('payment_status'=>$request->payment_status);
        DB::table('billings')->where('id',$request->id)->update($values);

        return response()->json(['error'=>false]);
    }
    
    public function salesReporting(Request $request){
        if(!isset($request->year)){
            $selectedYear = '2025';
        }else{
            $selectedYear = $request->year;
        }

        $sales  = DB::table("billings")
            ->select(
            DB::raw("DATE_FORMAT(billings.created_at, '%m') as month"),
            DB::raw("DATE_FORMAT(billings.created_at, '%Y') as year"),
            DB::raw('sum(billings.transport) as transport'),
            DB::raw('sum(billings.discount) as discount'),
            DB::raw('sum((select sum(billing_items.amount) from billing_items where billing_items.billing_id=billings.id)) as amount')
        )
        ->where(DB::raw("DATE_FORMAT(billings.created_at, '%Y')"),'=',$selectedYear)
        ->groupBy('month','year')
        ->get();
        
        return view('admin/sales_reporting',['sales'=>$sales,'selectedYear'=>$selectedYear,'title'=>'AR Clean Sales Reporting']);
    }

    public function salesByDate(Request $request){
        $result = DB::table('billing_items')->leftJoin('billings','billings.id','=','billing_items.billing_id')->where('billings.created_at',date('2024-01-08'))->sum('amount');
        return view('admin/sales_reporting',['amount'=>$result]);
    }

    public function discount(Request $request){
        $billings = DB::table('billings')->where('id',$request->billing_id)->get();
        return view('admin/billing_item_discount',['billings'=>$billings]);        
    }
    */
    
    public function discountSave(Request $request){
        $values = array(
            'discount'=>$request->discount,
            'pajak'=>$request->pajak,
            'transport'=>$request->transport,
            'termin'=>$request->termin,
            'duedate_at'=>$request->duedate
            );
            
        CustomBilling::where('id',$request->billing_id)->update($values);
        
        return response()->json(['status'=>'sukses','message'=>'Update data berhasil!']);
    }

    public function createInvoice(Request $request)
    {
        $billings = CustomBilling::leftJoin('customers','customers.id','=','custom_billings.customer_id')
            ->select('custom_billings.*','customers.name','customers.phone','customers.email','customers.address')
            ->where('custom_billings.id',$request->billing_id)
            ->get();
            
        $billingItems = CustomBillingItem::where('billing_id',$request->billing_id)->get();

        return view('admin/invoice_custom',['billing'=>$billings[0],'billingItems'=>$billingItems,'title'=>'AR Clean Invoice']);
    }

    public function searchCustomer(Request $request){
        return response()->json(['data'=>Customer::where('name','LIKE',"%{$request->q}%")->get()]);
    }    
    
}
?>