<?php

namespace App\Http\Controllers;

use App\Models\Order;
use App\Models\Customer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class DebtController extends Controller
{
    /**
     * Display debt management dashboard
     */
    public function index(Request $request)
    {
        $query = Order::with(['customer', 'orderItems.laundryItem'])
            ->where('outstanding_balance', '>', 0);

        // Filter by customer if specified
        if ($request->filled('customer_id')) {
            $query->where('customer_id', $request->customer_id);
        }

        // Filter by status if specified
        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        // Filter by date range if specified
        if ($request->filled('date_from')) {
            $query->whereDate('created_at', '>=', $request->date_from);
        }

        if ($request->filled('date_to')) {
            $query->whereDate('created_at', '<=', $request->date_to);
        }

        $orders = $query->orderBy('created_at', 'desc')->paginate(20);

        // Calculate summary statistics
        $totalOutstanding = Order::where('outstanding_balance', '>', 0)->sum('outstanding_balance');
        $totalOrders = Order::where('outstanding_balance', '>', 0)->count();
        $averageDebt = $totalOrders > 0 ? $totalOutstanding / $totalOrders : 0;

        // Get customers with outstanding balances
        $customersWithDebt = Customer::whereHas('orders', function($query) {
            $query->where('outstanding_balance', '>', 0);
        })->withSum(['orders' => function($query) {
            $query->where('outstanding_balance', '>', 0);
        }], 'outstanding_balance')->get();

        return view('debt.index', compact(
            'orders', 
            'totalOutstanding', 
            'totalOrders', 
            'averageDebt',
            'customersWithDebt'
        ));
    }

    /**
     * Show detailed debt information for a customer
     */
    public function customer(Customer $customer)
    {
        $orders = $customer->orders()
            ->with(['orderItems.laundryItem'])
            ->where('outstanding_balance', '>', 0)
            ->orderBy('created_at', 'desc')
            ->get();

        $totalDebt = $orders->sum('outstanding_balance');
        $totalPaid = $orders->sum('amount_paid');
        $totalAmount = $orders->sum('final_amount');

        return view('debt.customer', compact(
            'customer',
            'orders',
            'totalDebt',
            'totalPaid',
            'totalAmount'
        ));
    }

    /**
     * Generate debt report
     */
    public function report(Request $request)
    {
        $dateFrom = $request->input('date_from', now()->subMonth()->format('Y-m-d'));
        $dateTo = $request->input('date_to', now()->format('Y-m-d'));

        // Orders with outstanding balance
        $ordersWithDebt = Order::with(['customer'])
            ->where('outstanding_balance', '>', 0)
            ->whereBetween('created_at', [$dateFrom, $dateTo])
            ->get();

        // Summary by status
        $debtByStatus = Order::where('outstanding_balance', '>', 0)
            ->whereBetween('created_at', [$dateFrom, $dateTo])
            ->select('status', DB::raw('COUNT(*) as count'), DB::raw('SUM(outstanding_balance) as total'))
            ->groupBy('status')
            ->get();

        // Top debtors
        $topDebtors = Customer::whereHas('orders', function($query) use ($dateFrom, $dateTo) {
            $query->where('outstanding_balance', '>', 0)
                  ->whereBetween('created_at', [$dateFrom, $dateTo]);
        })->withSum(['orders' => function($query) use ($dateFrom, $dateTo) {
            $query->where('outstanding_balance', '>', 0)
                  ->whereBetween('created_at', [$dateFrom, $dateTo]);
        }], 'outstanding_balance')
        ->orderBy('orders_sum_outstanding_balance', 'desc')
        ->limit(10)
        ->get();

        return view('debt.report', compact(
            'ordersWithDebt',
            'debtByStatus',
            'topDebtors',
            'dateFrom',
            'dateTo'
        ));
    }

    /**
     * Send payment reminder SMS
     */
    public function sendReminder(Order $order)
    {
        if ($order->outstanding_balance <= 0) {
            return redirect()->back()->with('error', 'This order has no outstanding balance.');
        }

        try {
            $smsService = new \App\Services\SmsService();
            $message = "Hi {$order->customer->full_name}, this is a friendly reminder that your laundry order {$order->order_number} has an outstanding balance of N" . number_format($order->outstanding_balance, 2) . ". Please visit us to settle it. Thank you for choosing us.";

            $result = $smsService->sendSms(
                $order->customer->phone,
                $message,
                ['ref_id' => 'PAYMENT_REMINDER_' . $order->order_number . '_' . time()]
            );

            return redirect()->back()->with('success', 'Payment reminder sent successfully!');
        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'Failed to send payment reminder: ' . $e->getMessage());
        }
    }

    /**
     * Send consolidated payment reminder SMS for all outstanding orders
     */
    public function sendConsolidatedReminder(Customer $customer)
    {
        $orders = $customer->orders()
            ->where('outstanding_balance', '>', 0)
            ->get();

        $totalDebt = $orders->sum('outstanding_balance');
        $orderCount = $orders->count();

        if ($totalDebt <= 0) {
            return redirect()->back()->with('error', 'This customer has no outstanding debt.');
        }

        try {
            $smsService = new \App\Services\SmsService();
            // "Hi {Name}, Reminder: You have {Count} unpaid orders totaling N{Amount}. Please visit us to settle. Thanks, Slarry Laundry."
            $message = "Hi {$customer->full_name}, Reminder: You have {$orderCount} unpaid orders totaling N" . number_format($totalDebt, 2) . ". Please visit us to settle. Thanks, Slarry Laundry.";

            $result = $smsService->sendSms(
                $customer->phone,
                $message,
                ['ref_id' => 'DEBT_REMINDER_ALL_' . $customer->id . '_' . time()]
            );

            return redirect()->back()->with('success', 'Consolidated payment reminder sent successfully!');
        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'Failed to send reminder: ' . $e->getMessage());
        }
    }

    /**
     * Print customer debt statement
     */
    public function printStatement(Customer $customer)
    {
        $orders = $customer->orders()
            ->where('outstanding_balance', '>', 0)
            ->orderBy('created_at', 'asc')
            ->get();

        $totalDebt = $orders->sum('outstanding_balance');

        return view('debt.print', compact('customer', 'orders', 'totalDebt'));
    }



    /**
     * Delete an order (Admin only)
     */
    public function deleteOrder(Order $order)
    {
        // Check if user has permission to delete orders
        if (!\Illuminate\Support\Facades\Auth::user()->hasPermission('delete_customers')) {
            return redirect()->back()->with('error', 'You do not have permission to delete orders.');
        }

        try {
            $orderNumber = $order->order_number;
            $customerName = $order->customer->full_name;

            // Delete order items first (due to foreign key constraints)
            $order->orderItems()->delete();

            // Delete status history
            $order->statusHistory()->delete();

            // Delete the order
            $order->delete();

            return redirect()->route('debt.index')
                ->with('success', "Order {$orderNumber} for {$customerName} has been deleted successfully!");

        } catch (\Exception $e) {
            return redirect()->back()
                ->with('error', 'Failed to delete order: ' . $e->getMessage());
        }
    }
}
