<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

class VoucherController extends Controller
{
    /**
     * Display vouchers list
     */
    public function index()
    {
        $vouchers = DB::table('vouchers')
            ->orderBy('created_at', 'desc')
            ->paginate(20);
        
        $stats = [
            'total' => DB::table('vouchers')->count(),
            'active' => DB::table('vouchers')->where('is_active', true)->count(),
            'expired' => DB::table('vouchers')
                ->where('valid_until', '<', now())
                ->count(),
            'used_today' => DB::table('voucher_usage')
                ->whereDate('created_at', today())
                ->count(),
        ];
        
        return view('account.vouchers.index', compact('vouchers', 'stats'));
    }
    
    /**
     * Store new voucher
     */
    public function store(Request $request)
{
    $validated = $request->validate([
        'code' => 'required|string|max:50|unique:vouchers,code',
        'type' => 'required|in:percentage,fixed',
        'value' => 'required|numeric|min:0',
        'min_purchase' => 'required|integer|min:0',
        'max_discount' => 'nullable|integer|min:0',
        'max_usage' => 'required|integer|min:0',
        'valid_from' => 'nullable|date',
        'valid_until' => 'nullable|date|after:valid_from',
        'description' => 'nullable|string',
    ]);
    
    // Convert code to uppercase
    $validated['code'] = strtoupper($validated['code']);
    
    // ⭐ FIX: If valid_from is empty, set to NOW
    $validFrom = $validated['valid_from'] ?? now();
    
    // ⭐ FIX: If valid_until is empty, set to 1 month from now
    $validUntil = $validated['valid_until'] ?? now()->addMonth();
    
    DB::table('vouchers')->insert([
        'code' => $validated['code'],
        'type' => $validated['type'],
        'value' => $validated['value'],
        'min_purchase' => $validated['min_purchase'],
        'max_discount' => $validated['max_discount'] ?? null,
        'max_usage' => $validated['max_usage'],
        'valid_from' => $validFrom, // ⭐ CHANGED
        'valid_until' => $validUntil, // ⭐ CHANGED
        'description' => $validated['description'] ?? null,
        'is_active' => true,
        'used_count' => 0,
        'created_at' => now(),
        'updated_at' => now(),
    ]);
    
    return back()->with('success', 'Voucher created successfully!');
}
    
    /**
     * Update voucher
     */
    public function update(Request $request, $id)
{
    $validated = $request->validate([
        'type' => 'required|in:percentage,fixed',
        'value' => 'required|numeric|min:0',
        'min_purchase' => 'required|integer|min:0',
        'max_discount' => 'nullable|integer|min:0',
        'max_usage' => 'required|integer|min:0',
        'valid_from' => 'nullable|date',
        'valid_until' => 'nullable|date|after:valid_from',
        'description' => 'nullable|string',
    ]);
    
    // ⭐ Get current voucher data for fallback
    $currentVoucher = DB::table('vouchers')->where('id', $id)->first();
    
    DB::table('vouchers')
        ->where('id', $id)
        ->update([
            'type' => $validated['type'],
            'value' => $validated['value'],
            'min_purchase' => $validated['min_purchase'],
            'max_discount' => $validated['max_discount'] ?? null,
            'max_usage' => $validated['max_usage'],
            'valid_from' => $validated['valid_from'] ?? $currentVoucher->valid_from ?? now(),
            'valid_until' => $validated['valid_until'] ?? $currentVoucher->valid_until,
            'description' => $validated['description'] ?? null,
            'updated_at' => now(),
        ]);
    
    return back()->with('success', 'Voucher updated successfully!');
}
    
    /**
     * Toggle voucher status
     */
    public function toggleStatus($id)
    {
        $voucher = DB::table('vouchers')->where('id', $id)->first();
        
        DB::table('vouchers')
            ->where('id', $id)
            ->update([
                'is_active' => !$voucher->is_active,
                'updated_at' => now(),
            ]);
        
        return back()->with('success', 'Voucher status updated!');
    }
    
    /**
     * Delete voucher
     */
    public function destroy($id)
    {
        DB::table('voucher_usage')->where('voucher_id', $id)->delete();
        DB::table('vouchers')->where('id', $id)->delete();
        
        return back()->with('success', 'Voucher deleted successfully!');
    }
    
    /**
     * View voucher usage history
     */
    public function usage($id)
    {
        $voucher = DB::table('vouchers')->where('id', $id)->first();
        
        if (!$voucher) {
            abort(404);
        }
        
        $usage = DB::table('voucher_usage')
            ->where('voucher_id', $id)
            ->orderBy('created_at', 'desc')
            ->paginate(50);
        
        return view('account.vouchers.usage', compact('voucher', 'usage'));
    }
}