<?php

namespace App\Http\Controllers;

use App\Models\ActivityPermission;
use App\Models\ActivityPurchasePermission;
use Illuminate\Http\Request;
use App\Models\Stock;
use App\Models\Clients;
use App\Models\ColumnPermission;

use App\Models\ReportPermission;
use App\Models\RowPermissions;
use App\Models\User;
use App\Models\Users;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use PHPUnit\Framework\Constraint\Count;

class PermissionController extends Controller
{
    
    function createPrivilageForReports(Request $request)
    {
        $userID = $request->userID;
        $clientID = $request->clientID;

        $report = [ 'Stock Report' , 'Purchase Report' , 'Sale Report' , 'Edit DeleteReport' , 'Cash Closing Report', 'Login Report'];
        $slug = [ 'STKRPT','PURRPT','SALERPT','EDTDLTRPT','CASHCLORPT','LOGINRPT' ];

        for( $i = 0; $i< Count($report); $i++ )
        {
            $acPer = new ReportPermission();

            $acPer->user_id = $userID;
            $acPer->client_id = $clientID;
            $acPer->report_type = $report[$i];
            $acPer->slug_url = $slug[$i];
    
            $acPer->save();
        }

        $list = ReportPermission::where('user_id','=',$userID)->get();

        if(  count($list) == 6 )
        {
            return back()->with('success', 'Purchare report privilage granted successfully' );
        }
        else
        {
    
            return back()->with('fail', 'Something went wrong');
        }

    }



    function createPurchasePermissionsForUser(Request $request)
    {
        $userID = $request->userID;
        $clientID = $request->clientID;

        $acPer = new ActivityPurchasePermission();

        $acPer->user_id = $userID;
        $acPer->client_id = $clientID;

        $save = $acPer->save();

        if($save)
        {
            return back()->with('success', 'Purchare report privilage granted successfully' );
        }
        else
        {
            return back()->with('fail', 'Something went wrong');
        }

    }

    function createSalePermissionsForUser(Request $request)
    {
        $userID = $request->userID;
        $clientID = $request->clientID;

        $acPer = new ActivityPermission();

        $acPer->user_id = $userID;
        $acPer->client_id = $clientID;

        $save = $acPer->save();

        if($save)
        {
            return back()->with('success', 'Sale report privilage granted  successfully' );
        }
        else
        {
            return back()->with('fail', 'Something went wrong');
        }

    }

    function updateUserPermission(Request $request)
    {
        $user = ActivityPermission::where('user_id', '=', $request->userid)->pluck('id');
        $column = $request->column;
        $status = $request->status;

        $query = "UPDATE tbl_activitypermission SET " . $column . " = " . $status . " WHERE id = " . $user[0];

        $res = DB::statement($query);

        if ($res) {
            return response()->json(['success' => true, 'message' => 'Permission updated successfully' ], 200);
        } else {
            return response()->json(['fail' => false, 'message' => 'Something went wrong' ], 200);
        }
    }

    function updateUserPurchasePermission(Request $request)
    {
        $user = ActivityPurchasePermission::where('user_id', '=', $request->userid)->pluck('id');
        $column = $request->column;
        $status = $request->status;

        $query = "UPDATE tbl_activitypurchasepermission SET " . $column . " = " . $status . " WHERE id = " . $user[0];

        $res = DB::statement($query);

        if ($res) {
            return response()->json(['success' => true, 'message' => 'Permission updated successfully' ], 200);
        } else {
            return response()->json(['fail' => false, 'message' => 'Something went wrong' ], 200);
        }
    }


    function manageUserPermissions($userid, $clientid)
    {
        $user = Crypt::decrypt($userid);
        $client = Crypt::decrypt($clientid);

        $username = Users::where('id','=',$user)->pluck('Name');
        $email = Users::where('id','=',$user)->pluck('UserName');

        $ShopNam = Clients::where('ClientID','=',$client)->pluck('ClientName');
        $ShopLocation = Clients::where('ClientID','=',$client)->pluck('Location');
        $ShopArea = Clients::where('ClientID','=',$client)->pluck('Area');

        $data = [
            'userid' => $user,
            'clientID' => $client,

            'username' => $username[0],
            'email' => $email[0],
            'shopName' => $ShopNam[0],
            'shopLocation' => $ShopLocation[0],
            'shopArea' => $ShopArea[0],
            
            'sale' => ActivityPermission::where('user_id', '=', $user)->get(),
            'purchase' => ActivityPurchasePermission::where('user_id', '=', $user)->get(),
            'reports' => ReportPermission::where('user_id', '=', $user)->get(),
        ];

        return view('Admin.userPermissions', $data);
        // return $data;
    }









    function updateAppLoginStatus($id)
    {
        $uId = Crypt::decrypt($id);

        $user = Users::find($uId);

        if ($user->Active == 0) {
            $user->Active = 1;
            $user->save();

            return back()->with('success', 'App login enabled successfully');
        } else {
            $user->Active = 0;
            $user->save();

            return back()->with('success', 'App login disabled successfully');
        }
    }


    function updatewebpermissionstatus($id)
    {
        $uId = Crypt::decrypt($id);

        $user = Users::find($uId);

        if ($user->isWebLogin == 0) {
            $user->isWebLogin = 1;
            $user->save();

            return back()->with('success', 'Web login enabled successfully');
        } else {
            $user->isWebLogin = 0;
            $user->save();

            return back()->with('success', 'Web login disabled successfully');
        }
    }

    function managecolumnpermissions($slug, $hash)
    {
        // return $slug . "<br>" . $hash;

        $clientID = Crypt::decrypt($hash);

        $data = [
            'slug' => $slug,
            'clientid' => $clientID,
            'clientName' => Clients::where('ClientID', '=', $clientID)->pluck('ClientName'),
            'reportName' => ReportPermission::where('slug_url', '=', $slug)
                ->where('client_id', '=', $clientID)
                ->pluck('report_type'),
            'columns' => ColumnPermission::where('client_id', '=', $clientID)
                ->where('slug_url', '=', $slug)
                ->get()
        ];

        return view('Admin.columnpermissions', $data);
    }

    function managerowpermissions($slug, $hash)
    {
        // return $slug . "<br>" . $hash;

        $clientID = Crypt::decrypt($hash);

        $data = [
            'slug' => $slug,
            'clientid' => $clientID,
            'clientName' => Clients::where('ClientID', '=', $clientID)->pluck('ClientName'),
            'reportName' => ReportPermission::where('slug_url', '=', $slug)
                ->where('client_id', '=', $clientID)
                ->pluck('report_type'),

            'rows' => RowPermissions::where('client_id', '=', $clientID)
                ->where('slug_url', '=', $slug)
                ->get()
        ];

        return view('Admin.rowpermissions', $data);
    }


    function managePermissions($hash)
    {
        $id = Crypt::decrypt($hash);
        $data = [
            'clientID' => $id,
            'reports' => ReportPermission::where('client_id', '=', $id)->get(),
            'clients' => Clients::where('ClientID', '=', $id)->get(),
            'clientname' => Clients::where('ClientID', '=', $id)->pluck('ClientName')

        ];
        return view('Admin.managepermissions', $data);
    }


    function managePermissionsajax(Request $request)
    {
        $clientid = $request->client;

        $data = [
            'clientID' => $clientid,
            'reports' => ReportPermission::where('client_id', '=', $clientid)->get(),
            'clients' => Clients::where('ClientID', '=', $clientid)->get(),
            'clientname' => Clients::where('ClientID', '=', $clientid)->pluck('ClientName')

        ];

        $loadContent = '';

        $loadContent .= '<table data-page-length="10" id="example2" class="table table-striped table-bordered">
        <thead class="table-secondary">
            <tr>
                <th>Sl No</th>
                <th>Report Type</th>
                <th>Slug</th>
                <th>Mode</th>
                <th>Mode Management</th>

                <th>Column Permissions</th>
            </tr>
        </thead>

        <tbody>';


        $num = 1;

        foreach ($data['reports'] as $rpt) {

            $loadContent .= '
                <tr>
                <td> ' . $num . ' </td>
                <td> ' . $rpt->report_type . ' </td>
                <td> ' . $rpt->slug_url . '  </td>

                ';

            if ($rpt->status == 1) {
                $loadContent .= '<td>  <label class="text-success">Enabled</label>  </td>';
            } else {
                $loadContent .= '<td>  <label class="text-danger">Disabled</label>  </td>';
            }


            $loadContent .=  '<td>';

            if ($rpt->status == 0) {
                $loadContent .= '<form method="post" id="toggleForm">
                        <div class="form-check form-switch">
                            <input hidden name="rowid" type="text" value="' . $rpt->id . '">

                            <input type="checkbox" data-id="' . $rpt->id . '" name="status" class="js-switch" ' . $rpt->status == 1 ? "checked" : "";
                '>

                            <label class="form-check-label text-success" for="flexSwitchCheckChecked">ENABLE</label>

                        </div>
                    </form>';
            } else {
                $loadContent .= '<form method="post" id="toggleForm">
                        <div class="form-check form-switch">
                            <input hidden name="rowid" type="text" value="' . $rpt->id . '">

                            <input type="checkbox" data-id="' . $rpt->id . '" name="status" class="js-switch" ' . $rpt->status == 1 ? "checked" : "";
                '>

                            <label class="form-check-label text-danger" for="flexSwitchCheckChecked">DISABLE</label>

                        </div>
                    </form>';
            }

            $loadContent .=  '</td>


                <td>
                    <div class="table-actions d-flex align-items-center gap-3 fs-6">

                        <div class="col">
                            <button type="button" class="btn btn-primary px-5">Manage</button>
                        </div>


                        <!-- <a   data-bs-toggle="tooltip" data-bs-placement="bottom" title="Delete"><i class="bi bi-trash-fill"></i></a> -->
                    </div>
                </td>

            </tr>
            ';
            $num++;
        }

        $loadContent .= ' </tbody> </table>';

        return $loadContent;
    }


    function viewStockReport()
    {

        $data = [

            'clientname' => Clients::where('ClientID', '=', '2877')->pluck('ClientName'),

            'tablehead' => ColumnPermission::select('*')
                ->where('slug_url', '=', 'STKRPT')
                ->where('client_id', '=', '2877')
                ->where('column_status', '=', 1)
                ->get(),

            'stock' => Stock::select(
                'Product_Name',
                'Batch',

                DB::raw("SUBSTRING(Expiry,1, 10) as Expiry"),

                'uPack',
                DB::raw("purchase_quantity-sales_quantity as stock"),
                DB::raw("ROUND(Unit_Rate * uPack,2) as purchaserate"),
                DB::raw("ROUND( (Unit_Rate * uPack) * (purchase_quantity-sales_quantity),2 ) as purchasetotal"),
                DB::raw("  ROUND((MRP * uPack) / uPack ,2) as MRP"),
                DB::raw("((MRP * uPack) / uPack ) * (Purchase_quantity-sales_quantity) as mrptotal"),
                DB::raw("MRP * uPack as mrpperpack"),
                DB::raw("ROUND(Sales_Rate, 2) as Sales_Rate"),
                DB::raw(" ROUND(Sales_Rate * (Purchase_quantity-sales_quantity),2) as saleratetotal"),
                DB::raw("ROUND(Sales_Rate * uPack,2) as salerateperpack"),
            )
                ->where('ClientID', '=', '2877')

                ->get()
        ];

        // foreach($data['stock'] as $stock)
        // {
        //     echo $stock;
        //     echo '<br>';
        // }


        // return $data['stock'][0]['Product_Name'];
        // return $data['tablehead'][0]['column_key'];

        return view('Admin.viewStockReport', $data);
    }


    function updateReportPermissionStatus(Request $request)
    {

        $rowid = $request->user_id;
        $status = $request->status;

        $rptPer = ReportPermission::find($rowid);

        $rptPer->status = $status;

        $save =  $rptPer->save();

        if ($save) {
            return response()->json(['message' => 'true']);
        } else {
            return response()->json(['message' => 'false']);
        }
    }

    function updatepermissions(Request $request)
    {

        $rowid = $request->rowid;
        // $status = $request->status;

        if ($request->status == 'on') {
            $rptPer = ReportPermission::find($rowid);

            $rptPer->status = 1;

            $save =  $rptPer->save();

            if ($save) {
                return back()->with('success', 'Updated successfully');
            } else {
                return back()->with('fail', 'Failed to update');
            }
        } else {
            $rptPer = ReportPermission::find($rowid);

            $rptPer->status = 0;

            $save =  $rptPer->save();

            if ($save) {
                return back()->with('success', 'Updated successfully');
            } else {
                return back()->with('fail', 'Failed to update');
            }
        }
        return $request->status;
    }


    function updateColumnPermissions(Request $request)
    {

        $rowid = $request->rowid;
        // $status = $request->status;

        if ($request->status == 'on') {
            $rptPer = ColumnPermission::find($rowid);

            $rptPer->column_status = 1;

            $save =  $rptPer->save();

            if ($save) {
                return back()->with('success', 'Updated successfully');
            } else {
                return back()->with('fail', 'Failed to update');
            }
        } else {
            $rptPer = ColumnPermission::find($rowid);

            $rptPer->column_status = 0;

            $save =  $rptPer->save();

            if ($save) {
                return back()->with('success', 'Updated successfully');
            } else {
                return back()->with('fail', 'Failed to update');
            }
        }
        return $request->status;
    }

    function updateRowPermissions(Request $request)
    {

        $rowid = $request->rowid;
        // $status = $request->status;

        if ($request->status == 'on') {

            $rptPer = RowPermissions::find($rowid);

            $rptPer->row_status = 1;

            $save =  $rptPer->save();

            if ($save) {
                return back()->with('success', 'Updated successfully');
            } else {
                return back()->with('fail', 'Failed to update');
            }
        } else {
            $rptPer = RowPermissions::find($rowid);

            $rptPer->row_status = 0;

            $save =  $rptPer->save();

            if ($save) {
                return back()->with('success', 'Updated successfully');
            } else {
                return back()->with('fail', 'Failed to update');
            }
        }
        return $request->status;
    }
}
