<?php
namespace App\Http\Controllers;

use App\Http\Requests;
use Illuminate\Http\Request;
use DB;
use App\Main;
use App\Sort;
use App\Branch;
use App\Store_Branch;
use App\Store_History;
use App\Payment_Method;
use App\Supplier;
use App\Waste;
use App\Packingmethod;
use App\Physicalcondition;
use App\Driver;
use App\Vehicle;
use App\User;
use App\Customer;
use Carbon\Carbon;
use Auth;
use App\Safe_Account;
use App\Client;
use App\Invoice;
use App\Invoice_Item;
use App\Invoice_Payment;
use App\Cheque;
use App\Bank;
use App\Client_Sheet;
use App\Receipt;
use App\Safe_History;
use App\Review;
use App\Review_Item;
use App\Notifications;

class ReviewController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }



public function SendNotification ( $noti){

$action ="   أشعار المرتجعات ";


$onesignalAppId = "a7e5d801-ffac-42aa-8551-e7e6e26380e6";
$onesignalApiKey = "os_v2_app_u7s5qap7vrbkvbkr47toey4a4y5y4l4mh4dev5ejtqbatrgeb6cysaaley7g5x7r33dfyjkjqaaky2ujg6nyl5g6crocufk3dk4leey";

// محتوى الإشعار
$heading = array(
    "en" => $action
);
$content = array(
    "en" => " $noti "
);

$data = array(
    "screen" => "Notificationstore"
);

// بيانات الإشعار
$fields = array(
    'app_id' => $onesignalAppId,
    'included_segments' => array('All'), // أو تستخدم 'include_player_ids' لمستخدمين محددين
    'headings' => $heading,
    'contents' => $content,
    'data' => $data,
  

);

$fields = json_encode($fields);

$ch = curl_init();
//curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/");
curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json; charset=utf-8',
    'Authorization: Basic ' . $onesignalApiKey
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

$response = curl_exec($ch);
curl_close($ch);

//print_r($response);


}



    
    public function saveReview(Request $request)
    {
        

        DB::beginTransaction();

       
       try {
            // 1. حفظ بيانات المراجعة الأساسية
            $review = Review::create([
                'client_id' => $request->client_id,
                'invoice_id' => $request->invoice_id,
                'reason' => $request->reason,
                'received_by' => $request->received_by,
                'notes' => $request->notes,
                'status' => 'pending',
                'total_price' => 0 // سيتم تحديثه بعد حساب الأصناف
            ]);

        
            $totalAmount = 0;

            // 2. حفظ أصناف المراجعة
            foreach ($request->items as $itemData) {
                $itemTotal = $itemData['price'] * $itemData['quantity'];
                $totalAmount += $itemTotal;

                Review_Item::create([
                    'review_id' => $review->id,
                    'item_id' => $itemData['item_id'],
                    'price' => $itemData['price'],
                    'quantity' => $itemData['quantity'],
                    'total' => $itemTotal
                ]);
            }

            // 3. تحديث المبلغ الإجمالي للمراجعة
            $review->update(['total_price' => $totalAmount]);

            DB::commit();



//added for notifivation

$admin_name = Auth::user()->name ;
$branch_name = Auth::user()->branch->name ;
$client_id = $request->client_id;
$client = Client::where( 'id', $client_id )->first(); 
$client_name = $client->name;
$action ="  أشعار المرتجعات   ";
$invoice_id = $request->invoice_id;
$reason = $request->reason;
$received_by = $request->received_by;



$n = Notifications::create ( [  'type'=>$action,'action'=>   " تم تسجيل عملية مرتجع بواسطة المستخدم  $admin_name  وذلك من العميل $client_name    بفرع $branch_name    عن الفاتورة رقم  $invoice_id     بقيمة أجمالية قدرها  $totalAmount  وقد تم استلام المرتجع بواسطة  $received_by / الملاحظة   $reason" ]);

$this->SendNotification (   " تم تسجيل عملية مرتجع بواسطة المستخدم  $admin_name  وذلك من العميل $client_name    بفرع $branch_name    عن الفاتورة رقم  $invoice_id     بقيمة أجمالية قدرها  $totalAmount  وقد تم استلام المرتجع بواسطة  $received_by / الملاحظة   $reason" );

//end notifivation

            return response()->json([
                'success' => true,
                'message' => 'تم حفظ المراجعة بنجاح',
                'review_id' => $review->id
            ]);
            
            

        } catch (\Exception $e) {
            DB::rollBack();
            
            return response()->json([
                'success' => false,
                'message' => 'حدث خطأ أثناء حفظ المراجعة',
                'error' => $e->getMessage()
            ], 500);
        }
            
    }



public function reviews_get()
{
    $reviews = Review::paginate(100);
    $branch_id = Auth::user()->branch_id ;
    
    return view('invoice.show_reviews', ['reviews' => $reviews ,'branch_id'=>$branch_id ]);
}

public function getReviewItems($review_id)
{
    $review = Review::with(['items.invoiceitem.sell_store'])->findOrFail($review_id);
    //echo $review;
     return view('invoice.show_reviewitems', ['review' => $review]);
}

public function saveReviewStatus(Request $request)
{
    
    $status = $request->status;
    if ($status == "refused"){
        
        Review::where('id', $request->review_id)
                      ->update([
                          'status' => 'rejected',
                          'updated_at' => Carbon::now()
                      ]);
          return redirect()->back()->with('error','transaction rejected');            
    }


DB::beginTransaction();
        
        try {
            // 1. إنشاء سجل جديد في client_sheet
            $newRecord = Client_Sheet::create([
                'created_at' => Carbon::now(),
                'leeh' => $request->amount,
                'aleeh' => 0,
                'client_id' => $request->client_id,
                'receipt_id' => null,
                'refused_cheque' => null,
                'review_id' => $request->review_id
            ]);
            
            Review::where('id', $request->review_id)
                      ->update([
                          'status' => $request->status,
                          'updated_at' => Carbon::now()
                      ]);
            
            // إتمام المعاملة
            DB::commit();
            
            return redirect()->back()->with('success', 'تمت عملية تسوية المرتجع بنجاح!');
            
        } catch (\Exception $e) {
            // التراجع عن المعاملة في حالة حدوث خطأ
            DB::rollBack();
            
            return redirect()->back()->with('error', 'حدث خطأ أثناء المعالجة: ' . $e->getMessage());
        }
    
    
    return back()->with('success', 'تم اعتماد المراجعة بنجاح');
}


}
