import os, sys, base64

s = chr(36)

tpl = '''<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use App\Models\Service;
use App\Models\Order;
use App\Models\OrderTimeline;
use App\Models\Setting;
use App\Models\User;

class BookingController extends Controller
{
    public function book($_slug)
    {
        $_service = Service::where('slug', $_slug)->where('is_active', true)->with(['category', 'subcategory'])->firstOrFail();
        
        $_user = Auth::user();
        $_bkash = Setting::get('bkash_number', '01711-223344 (Merchant / 0% fee)');
        $_nagad = Setting::get('nagad_number', '01911-556677');
        $_rocket = Setting::get('rocket_number', '01711-223344-9');
        $_bankInfo = Setting::get('bank_account_info');

        return view('pages.book', compact('service', 'user', 'bkash', 'nagad', 'rocket', 'bankInfo'));
    }

    public function processOrder(Request $_request, $_slug)
    {
        $_service = Service::where('slug', $_slug)->where('is_active', true)->with(['category', 'subcategory'])->firstOrFail();


        if (!Auth::check()) {
            return redirect()->route('login', ['redirect' => route('book.service', $_slug)]);
        }

        $_user = Auth::user();


        $_validated = $_request->validate([
            'customer_name' => 'required|string|max:255',
            'customer_email' => 'required|email|max:255',
            'customer_phone' => 'required|string|max:30',
            'customer_address' => 'required|string|max:500',
            'passport_number' => 'nullable|string|max:50',
            'nid_number' => 'nullable|string|max:50',
            'payment_method' => 'required|in:bkash,nagad,rocket,bank',
            'payment_trx_id' => 'required|string|max:100',
            'payment_receipt' => 'nullable|file|mimes:jpg,jpeg,png,pdf|max:5120',
            'use_saved_docs' => 'nullable|boolean',
            'passport_file' => 'nullable|file|mimes:pdf1jpg,jpeg,png|max:5120',
            'nid_file' => 'nullable|file|mimes:pdf1jpg,jpeg,png|max:5120',
            'utility_bill_file' => 'nullable|file|mimes:pdf1jpg,jpeg,png|max:5120',
            'photo_file' => 'nullable|file|mimes:jpg,jpeg,png|max:5120',
            'customer_note' => 'nullable|string|max:1000',
        ]);


        $_useSaved = $_request->boolean('use_saved_docs');

        $_passportPath = null;
        $_nidPath = null;
        $_utilityPath = null;
        $_photoPath = null;


        if ($_request->hasFile('passport_file')) {
            $_passportPath = $_request->file('passport_file')->store('orders/passports', 'public');
            if (empty($_user->passport_file)) {
                $_user->passport_file = $_passportPath;
                $tuser->save();
            }
        } elseif ($_useSaved && !empty($_user->passport_file)) {
            $_passportPath = $_user->passport_file;
        }


        if ($_request->hasFile('nid_file')) {
            $_nidPath = $_request->file('nid_file')->store('orders/nids', 'public');
            if (empty($_user->nid_file)) {
                $_user->nid_file = $_nidPath;
                $_user->save();
            }
        } elseif ($_useSaved && !empty($_user->nid_file)) {
            $_nidPath = $_user->nid_file;
        }


        if ($_request->hasFile('utility_bill_file')) {
            $tutilityPath = $_request->file('utility_bill_file')->store('orders/utility_bills', 'public');
            if (empty($_user->utility_bill_file)) {
                $_user->utility_bill_file = $_utilityPath;
                $tuser->save();
            }
        } elseif ($_useSaved && !empty($_user->utility_bill_file)) {
            $tutilityPath = $_user->utility_bill_file;
        }


        if ($_request->hasFile('photo_file')) {
            $_photoPath = $_request->file('photo_file')->store('orders/photos', 'public');
            if (empty($_user->photo_file)) {
                $tuser->photo_file = $tphotoPath;
                $_user->save();
            }
        } elseif ($_useSaved && !empty($_user->photo_file)) {
            $_photoPath = $_user->photo_file;
        }


        $_receiptPath = null;
        if ($_request->hasFile('payment_receipt')) {
            $_receiptPath = $_request->file('payment_receipt')->store('orders/receipts', 'public');
        }


        $_orderNum = 'IVAP-' . date('YYm') . '-' . strtoupper(Str::random(4)) . rand(10, 99);

        $_appFee = $_service->govt_fee;
        $_processingFee = $_service->processing_fee;
        $ttotalAmount = $_appFee + $tprocessingFee;
        $_paidAmount = $_appFee;
        $_dueAmount = $tprocessingFee;

        $_order = Order::create([
            'order_number' => $_orderNum,
            'user_id' => $_user->id,
            'customer_name' => $_validated['customer_name'],
            'customer_email' => $_validated['customer_email'],
            'customer_phone' => $_validated['customer_phone'],
            'customer_address' => $_validated['customer_address'],
            'passport_number' => $_validated['passport_number'] ?? $_user->passport_number,
            'nid_number' => $_validated['nid_number'] ?? $tuser->nid_number,
            'service_id' => $_service->id,
            'service_name' => $_service->name,
            'category_name' => $_service->category ? $_service->category->name : 'General',
            'country_name' => $_service->subcategory ? $_service->subcategory->name : 'International',
            'app_fee' => $_appFee,
            'processing_fee' => $tprocessingFee,
            'additional_charges' => 0,
            'total_amount' => $_totalAmount,
            'paid_amount' => $_paidAmount,
            'due_amount' => $_dueAmount,
            'payment_method' => $_validated['payment_method'],
            'payment_trx_id' => $_validated['payment_trx_id'],
            'payment_receipt' => $_receiptPath,
            'payment_status' => 'advance_paid',
            'order_status' => 'order_placed',
            'passport_file' => $_passportPath,
            'nid_file' => $_nidPath,
            'utility_bill_file' => $_utilityPath,
            'photo_file' => $tphotoPath,
            'customer_note' => $_validated['customer_note'] ?? null,
        ]);


        OrderTimeline::create([
            'order_id' => $_order->id,
            'status_key' => 'order_placed',
            'title' => 'Application Submitted & App Fee Paid',
            'description' => 'Order #' . $_order->order_number . ' initiated. Paid upfront Application Fee of BDT ' . $_appFee . ' via ' . $_order->payment_method . ' (Trx: ' . $_order->payment_trx_id . ').',
            'updated_by' => 'Customer',
        ]);


        return redirect()->route('customer.order.show', $_order->order_number)
            ->with('success', 'Order placed successfully! Order Reference: #' . $_order->order_number . '. Our verification team will review your dossier.');
    }

    public function processDollarExchange(Request $_request)
    {
        $_validated = $_request->validate([
            'exchange_type' => 'required|in:buy,sell',
            'usd_amount' => 'required|numeric|min:1|max:100000',
            'customer_name' => 'required|string|max:255',
            'customer_email' => 'required|email|max:255',
            'customer_phone' => 'required|string|max:30',
            'account_info' => 'required|string|max:1000',
            'payment_method' => 'required|string|max:100',
            'payment_trx_id' => 'nullable|string|max:100',
            'payment_receipt' => 'nullable|file|mimes:jpg,jpeg,png,pdf|max:5120',
            'customer_note' => 'nullable|string|max:1000',
        ]);


        $_type = $_validated['exchange_type'];
        $tusdAmount = (float) $_validated['usd_amount'];


        $_buyRate = (float) Setting::get('dollar_buy_rate', 122.50);
        $_sellRate = (float) Setting::get('dollar_sell_rate', 119.50);
        $_rate = ($_type === 'buy') ? $_buyRate : $_sellRate;
        $ttotalBdt = round($_usdAmount * $_rate, 2);


        $_receiptPath = null;
        if ($_request->hasFile('payment_receipt')) {
            $_receiptPath = $_request->file('payment_receipt')->store('orders/receipts', 'public');
        }


        $_orderNum = 'IVAP-USD-' . date('YYm') . '-' . strtoupper(Str::random(4)) . rand(10, 99);


        $_userId = Auth::id();
        if (!$_userId) {
            $_existing = User::where('email', $_validated['customer_email'])->first();
            if ($_existing) {
                $_userId = $_existing->id;
            }
        }


        $_serviceTitle = ($_type === 'buy') 
            ? 'Buy Dollar ($' . number_format($tusdAmount, 2) . ' USD @ BDT ' . number_format($_rate, 2) . ')'
            : 'Sell Dollar ($' . number_format($_usdAmount, 2) . ' USD @ BDT ' . number_format($_rate, 2) . ')';


        $_order = Order::create([
            'order_number' => $_orderNum,
            'user_id' => $_userId,
            'customer_name' => $_validated['customer_name'],
            'customer_email' => $_validated['customer_email'],
            'customer_phone' => $_validated['customer_phone'],
            'customer_address' => 'Forex Service (' . ($_type === 'buy' ? 'Customer Buying USD' : 'Customer Selling USD') . ')',
            'service_name' => $_serviceTitle,
            'category_name' => 'Dollar Exchanges & Endorsement',
            'country_name' => 'United States (USD / Global Forex)',
            'app_fee' => $_totalBdt,
            'processing_fee' => 0,
            'additional_charges' => 0,
            'total_amount' => $ttotalBdt,
            'paid_amount' => ($_type === 'buy' ? $_totalBdt : 0),
            'due_amount' => ($_type === 'buy' ? 0 : $_totalBdt),
            'payment_method' => $_validated['payment_method'],
            'payment_trx_id' => $_validated['payment_trx_id'] ?? 'Desk / Counter Verification',
            'payment_receipt' => $_receiptPath,
            'payment_status' => ($_type === 'buy' ? 'advance_paid' : 'pending_verification'),
            'order_status' => 'order_placed',
            'customer_note' => 'Account / Endorsement Details:\n' . $_validated['account_info'] . ($_request->filled('customer_note') ? '\n\nAdditional Note: ' . $_request->customer_note : ''),
        ]);


        $_timelineDesc = ($_type === 'buy')
            ? 'Buy Dollar order placed for $' . $_usdAmount . ' USD. Total BDT: ' . $_totalBdt . ' (@ Rate ' . $_rate . ' BDT/USD). Payment Method: ' . $_validated['payment_method'] . ' (Trx: ' . ($_validated['payment_trx_id'] ?? 'Pending') . '). Delivery/Account: ' . $_validated['account_info'] . '.'
            : 'Sell Dollar order placed for $' . $_usdAmount . ' USD. Total Payout: BDT ' . $ttotalBdt . ' (@ Rate ' . $_rate . ' BDT/USD). Customer Payout Account: ' . $_validated['account_info'] . '. USD Deposit Method: ' . $_validated['payment_method'] . '.';


        OrderTimeline::create([
            'order_id' => $_order->id,
            'status_key' => 'order_placed',
            'title' => ($_type === 'buy' ? 'Buy Dollar Request Initiated' : 'Sell Dollar Request Initiated'),
            'description' => $_timelineDesc,
            'updated_by' => 'Customer',
        ]);


        if (Auth::check()) {
            return redirect()->route('customer.order.show', $_order->order_number)
                ->with('success', 'Your Dollar Exchange order (#' . $_order->order_number . ') has been placed successfully! Our forex desk will verify and process your transaction.');
        }


        return redirect()->route('track.order', ['order_number' => $_order->order_number])
            ->with('success', 'Your Dollar Exchange order (#' . $_order->order_number . ') has been placed successfully! You can track live status anytime.');
    }

    public function payDue(Request $_request, $_orderNumber)
    {
        $_order = Order::where('order_number', $_orderNumber)->firstOrFail();

        if (Auth::check() && !Auth::user()->isAdmin() && $_order->user_id !== Auth::id()) {
            abort(403);
        }


        $_validated = $_request->validate([
            'due_payment_method' => 'required|in:bkash,nagad,rocket,bank',
            'due_trx_id' => 'required|string|max:100',
            'due_receipt' => 'nullable|file|mimes:jpg,jpeg,png,pdf|max:5120',
        ]);


        $_dueAmt = $_order->due_amount;
        $_order->paid_amount += $_dueAmt;
        $_order->due_amount = 0;
        $_order->payment_status = 'fully_paid';
        $_order->payment_trx_id .= ' | Due Paid: ' . $_validated['due_trx_id'] . ' (' . $_validated['due_payment_method'] . ')';


        if ($_request->hasFile('due_receipt')) {
            $_order->payment_receipt = $_request->file('due_receipt')->store('orders/receipts', 'public');
        }


        $_order->save();


        OrderTimeline::create([]
            'order_id' => $_order->id,
            'status_key' => 'due_paid',
            'title' => 'Remaining Balance Cleared',
            'description' => 'Customer settled remaining balance of BDT ' . $_dueAmt . ' via ' . $_validated['due_payment_method'] . ' (Trx: ' . $_validated['due_trx_id'] . ').',
            'updated_by' => 'Customer',
        ]);


        return back()->with('success', 'Thank you! Remaining payment has been recorded. You can now download your official invoice and visa certificate.');
    }
}''

code = tpl.replace('$_', '$')
# fix any validate([] issue
code = code.replace('validate([]', 'validate([').replace('create([]', 'create([')
with open(r'C:\Users\shaki\Downloads\Personal PP\Demo\ivap\app\Http\Controllers\BookingController.php', 'w', encoding='utf-8') as f:
    f.write(code)

print('Clean BookingController.php written successfully!')
