<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Card;
use App\Models\Member;
use App\Models\PaymentProof;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Validator;

class CardRequestController extends Controller
{
	public function index() 
	{
		$items = Card::select('cards.*', 'members.name as member_name', 'members.email as member_email')
			->join('card_member', 'cards.id', '=', 'card_member.card_id')
			->join('members', 'card_member.member_id', '=', 'members.id')
			->whereNotNull('cards.parent_card_id')
			->whereIn('cards.is_active', [0, 2]) // 0: Pending, 2: Action Required
			->orderBy('card_member.updated_at', 'desc')
			->paginate(10);

		return view('admin.cards.requests_list', compact('items'));
	}

	public function approve($id)
	{
		$card = Card::findOrFail($id);
		$card->is_active = 1;
		$card->save();
		return redirect()->back()->with('success', 'تم تفعيل الكارت بنجاح');
	}


	public function handleAction(Request $request)
	{
		
		$action = $request->input('action');
		$ids = $request->input('ids');
		$inputPrice = $request->input('price');
		$paymentMethod = $request->input('payment');
		

		if ($action === 'mail') {
			//Log::info("Action: Mail | Count: " . count($ids));
			foreach ($ids as $id) {
				$data = DB::table('card_member')
					->join('members', 'card_member.member_id', '=', 'members.id')
					->where('card_member.card_id', $id)
					->select('members.email', 'members.name', 'card_member.card_id')
					->first();

				if ($data) {
					$bankDetails = $this->getBankDetailsByMethod($paymentMethod);
					$p_card = $this->getParentDetails($id);
					$price = \DB::table('card_settings')->where('card_id', $p_card->id)->value('price') ?? 0; 
					$currency = $p_card->currency;
					//Log::info("Sending Styled Mail to: " . $data->email);
					$locale = str_replace('_', '-', strtolower(app()->getLocale()));
					$viewData = [
						'member_name'      => $data->name,
						'card_title'       => $p_card->name ?? 'Standard Card',
						'amount'           => $price,
						'currency'         => $currency,
						'payment_method'   => $paymentMethod,
						'bank_details'     => $bankDetails,
						'admin_note'       => 'Please upload the payment receipt to proceed.',
						'confirmation_url' => url($locale . '/confirm/' . $data->card_id),
						'request_id'       => substr($data->card_id, 0, 8),
						'price'       => $price,
						'data'             => $data 
					];

					return view('emails.payment_request', $viewData, function ($message) use ($data) {
						$message->to($data->email)
								->subject("Payment Request - Card Information");
					});
					session()->flash('toast', 'aaaaaaaaaaaaaaaaaaaa');
					//Log::info("Mail Sent Successfully without Errors!");
				} else {
					Log::error("No member linked to Card ID: " . $id);
				}
			}
			
			$message = 'Successfully sent!';
				session()->flash('toast', [
					'type' => 'success',
					'text' => $message,
					'size' => 'sm'
				]);
			return response()->json(['status' => 'success']); 
		}

		$message = "Error";
			session()->flash('toast', [
				'type' => 'error',
				'text' => $message,
				'size' => 'sm'
			]);
		return response()->json(['status' => 'error']);
	}
	/**
	 * Helper to return instructions based on payment method
	 */
	private function getBankDetailsByMethod($method) 
	{
		$methods = [
			'bank_transfer' => 'IBAN: EG6000... | Bank: International Bank',
			'cash'          => 'Visit our main branch for cash payment',
			'online'        => 'Follow the link below for credit card payment',
		];
		
		return $methods[$method] ?? 'Please contact administration for payment info';
	}
/**
 * Fetch payment proof details for the admin review modal.
 */
public function getPaymentProof($local, $id)
{
    $proof = DB::table('payment_proofs as pp')
        ->join('cards as c', 'pp.card_request_id', '=', 'c.id')
        ->join('card_member as cm', 'c.id', '=', 'cm.card_id')
        ->join('members as m', 'cm.member_id', '=', 'm.id')
        ->where('pp.card_request_id', $id)
        ->select(
            'c.name as card_type_name',
            'c.currency as card_currency',
            'pp.transaction_number',
            'pp.receipt_path',
            'pp.amount_paid',
            'pp.member_note',
            'pp.status',
			'pp.created_at',
            'm.name as customer_name',
            'm.email as customer_email'
            // I removed member_number because it's not in your members table or it has a different name
        )
        ->first();
    if ($proof) {
        // Return structured JSON response for the frontend modal or view
        return response()->json([
            'success' => true,
            'proof' => [
                'member_notes'      => $proof->member_note,
                'card_currency'      => $proof->card_currency,
                'customer_name'      => $proof->customer_name,
                'customer_email'     => $proof->customer_email,
                'transaction_number' => $proof->transaction_number,
                'amount_paid'        => $proof->amount_paid,
                'receipt_path'       => asset($proof->receipt_path),
                'member_note'        => $proof->member_note,
                'card_type_name'        => $proof->card_type_name,
                'created_at'         => $proof->created_at
            ]
        ]);
    }

    // Return error if no record matches the given ID
    return response()->json([
        'success' => false, 
        'message' => 'Payment proof not found for this card.'
    ], 404);
}

/**
 * Finalize activation: Update status, set dates, and log transaction.
 */
public function activateCard(Request $request) // الـ ID اللي جاي هو ID الكارت فعلياً
{
    // 1. كويري مباشر وصريح بيبدأ من الكارت اللي معاك الـ ID بتاعه
    $data = DB::table('cards')
        ->join('card_member', 'cards.id', '=', 'card_member.card_id')
        // بنربط التير من خلال النادي زي ما أنت عايز، بس بنأكد إن التير هو المربوط بالعضو
        ->join('tiers', 'card_member.tier_id', '=', 'tiers.id') 
        ->join('members', 'card_member.member_id', '=', 'members.id')
        ->where('cards.id', $request->request_id) // هنا البحث بـ ID الكارت مباشرة
        ->select(
            'card_member.member_id',
            'cards.id as actual_card_id',
            'tiers.price as tier_price',
            'tiers.points_threshold as balance',
            'tiers.name as tier_name'
        )
        ->first();

    // 2. تفتيش سريع: لو الكويري فاضي هيقولك ليه
    if (!$data) {
        // لو ملقاش، ده معناه إن الكارت ده مش مربوط بـ member في جدول card_member
        \Log::error("Activation Failed: Card ID $card_id not linked in card_member or tiers.");
        return redirect()->back()->with('error', 'بيانات الكارت أو العضو غير مكتملة في الداتابيز');
    }

    try {
        DB::beginTransaction();

        // 3. تفعيل الكارت (الحالة 1)
        DB::table('cards')->where('id', $data->actual_card_id)->update([
            'is_active' => 1,
            'issue_date' => $request->start_date,
            'expiration_date' => $request->expiry_date,
            'activated_at' => now()
        ]);

        // 4. تحديث سجل الدفع (Approved)
        DB::table('payment_proofs')->where('card_request_id', $data->actual_card_id)->update([
            'status' => 'verified'
        ]);

        // 5. تسجيل المعاملة المالية (Transaction)
        DB::table('transactions')->insert([
            'id' => (string) \Str::uuid(),
            'member_id' => $data->member_id,
            'card_id' => $data->actual_card_id,
            'event' => 'card_activation',
            'purchase_amount' => $data->tier_price,
            'points' => $data->balance ?? 0,
            'currency' => 'EGP',
            'note' => 'تفعيل كارت: ' . $data->tier_name,
            'created_at' => now(),
            'updated_at' => now(),
            'staff_id' => auth('staff')->id() ?? null,
        ]);

        DB::commit();
        return redirect()->back()->with('success', 'تم تفعيل الكارت بنجاح وتسجيل المعاملة');

    } catch (\Exception $e) {
        DB::rollBack();
        \Log::error("Activation Error: " . $e->getMessage());
        return redirect()->back()->with('error', 'حدث خطأ: ' . $e->getMessage());
    }
}
	/**
	 * Show the form for the customer to upload payment proof
	 */
	public function showConfirmationForm($locale,$card_id)
	{
		/* 
		$request_data =DB::table('card_member')
			->join('cards', 'card_member.card_id', '=', 'cards.id')
			->where('card_member.card_id', $card_id)
			->select(
				'card_member.*', 
				'cards.title as card_title'
			)
			->first(); */
			
	$request_data = DB::table('card_member')
			->join('cards', 'card_member.card_id', '=', 'cards.id')
			
			->join('members', 'card_member.member_id', '=', 'members.id')
			
			->join('tiers', 'cards.club_id', '=', 'tiers.club_id')
			
			->where('tiers.id', $card_id) 
			
			->select(
				'members.name as member_name',
				'members.email',
				'tiers.name as tier_name', 
				'tiers.points_threshold as tier_points_threshold',
				'tiers.points_multiplier as tier_points_multiplier',
				'tiers.redemption_discount as tier_redemption_discount',
				'tiers.color as tier_color',
				'tiers.price as tier_price',
				'tiers.id as tier_id',
				'tiers.points_threshold as balance'
			)
			->first();

		if (!$request_data) {
			abort(404, 'Invalid Request');
		}
		//dd($request_data);
		$price= \DB::table('card_settings')->where('card_id', $card_id)->value('price') ?? 0;

		return view('member.payment.confirm_form', compact('card_id','request_data','locale','price'));
	}

	/**
	 * Handle the uploaded proof from the customer
	 */
	public function submitConfirmation(Request $request)
	{
		$validator = Validator::make($request->all(), [
			'card_id'            => 'required',
			'transaction_number' => 'required|string',
			'receipt_photo'      => 'required|image|mimes:jpg,jpeg,png|max:2048',
		], [
			'receipt_photo.mimes' => 'عفواً، يجب أن تكون الصورة بصيغة jpg, jpeg, png فقط.',
			'receipt_photo.image' => 'الملف المرفوع يجب أن يكون صورة.',
			'receipt_photo.max'   => 'حجم الصورة كبير جداً، الحد الأقصى 2 ميجا.',
		]);
		
	if ($validator->fails()) {
			$message = $validator->errors()->first(); // بنجيب أول خطأ حصل
			
			session()->flash('toast', [
				'type' => 'error',
				'text' => $message,
				'size' => 'sm'
			]);
			
			return redirect()->back()->withErrors($validator)->withInput();
		}
		$filePath = null;
		if ($request->hasFile('receipt_photo')) {
			$file = $request->file('receipt_photo');
			$filename = time() . '_' . Str::slug($file->getClientOriginalName()) . '.' . $file->getClientOriginalExtension();
			$file->move(public_path('uploads/payments'), $filename);
			$filePath = 'uploads/payments/' . $filename;
		}

		try {
			$tier = DB::table('tiers')->where('id', $request->card_id)->first();

			if (!$tier) {
				return "Error: Tier not found in database for ID: " . $request->card_id;
			}
			$get_cart = DB::table('cards')
				->join('card_member', 'cards.id', '=', 'card_member.card_id')
				->where('cards.club_id', $tier->club_id) 
				->where('card_member.member_id', auth()->id())
				->select('cards.id as card_id')
				->first();

			if (!$get_cart) {
				return "Error: No card found for this member in Club ID: " . $tier->club_id;
			}
			if (!$get_cart) {
				\Log::error('No Data Found for Tier ID', ['tier_id' => $request->card_id]);
				return redirect()->back()->with('toast', ['type' => 'error', 'text' => 'البيانات غير متطابقة']);
			}

			 $p_card = $this->getParentDetails($get_cart->card_id);
			 
			//$price = \DB::table('card_settings')->where('card_id', $p_card->id)->value('price') ?? 0;
			DB::beginTransaction();
			PaymentProof::updateOrCreate(
				['card_request_id' => $get_cart->card_id],
				[
					'transaction_number' => $request->transaction_number,
					'amount_paid'        => $tier->price,
					'receipt_path'       => $filePath,
					'status'             => 'pending', // نرجع الحالة لـ pending للمراجعة من جديد
					'member_note'        => $request->note,
				]
			);
			

			// 4. التحديث في جدول cards (العمود is_active هناك)
			DB::table('cards')
				->where('id', $get_cart->card_id)
				->update(['is_active' => 2]);

			DB::commit();

			session()->flash('toast', [
				'type' => 'success',
				'text' => 'تم تحديث بيانات السداد بنجاح وجاري المراجعة.',
				'size' => 'sm'
			]);
			
			return redirect()->back()->with('success', 'تم تحديث بيانات السداد بنجاح وجاري المراجعة.');

		} catch (\Exception $e) {
			DB::rollBack();
			return redirect()->back()->withErrors(['error' => 'حدث خطأ: ' . $e->getMessage()]);
		}
	}
	/**
	 * Get parent card details including currency by child card reference.
	 * * @param string $cardIdOrNumber
	 * @return \App\Models\Card|null
	 */
	public function getParentDetails($cardIdOrNumber)
	{
		$childCard = Card::where('id', $cardIdOrNumber)
						 ->first();

		if ($childCard && $childCard->parent_card_id) {
			return Card::find($childCard->parent_card_id);
		}

		return $childCard;
	}

}