<?php

namespace App\Http\Controllers\Api;

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

class SalesmanVisitController extends Controller
{
    /**
     * Mendapatkan rute kunjungan salesman hari ini berdasarkan Master Journey Plan
     */
    public function getTodayRoutes(Request $request)
    {
        $user = $request->user();
        if (!$user || !$user->salesman_id) {
            return response()->json(['success' => false, 'message' => 'Data Salesman tidak ditemukan.'], 404);
        }

        $salesmanId = $user->salesman_id;
        $today = Carbon::today();
        $dayOfWeek = $today->dayOfWeekIso; // 1 (Senin) - 7 (Minggu)
        $weekOfMonth = $this->getWeekOfMonth($today);

        try {
            $routes = DB::table('master_journey_plans as mjp')
                ->join('customers as c', 'mjp.customer_id', '=', 'c.id')
                ->select('mjp.*', 'c.name as customer_name', 'c.address as customer_address', 'c.phone as customer_phone')
                ->where('mjp.salesman_id', $salesmanId)
                ->where('mjp.day_of_week', $dayOfWeek)
                ->where('mjp.is_active', true)
                // PERBAIKAN ENTERPRISE: Proteksi Kebocoran Master Plan Lintas Cabang
                ->where('c.branch_id', $user->branch_id)
                ->where(function ($query) use ($weekOfMonth) {
                    $query->where('mjp.frequency_type', 'weekly')
                        ->orWhere(function ($q) use ($weekOfMonth) {
                            $q->where('mjp.frequency_type', 'biweekly_odd')
                                ->whereRaw('? % 2 != 0', [$weekOfMonth]);
                        })
                        ->orWhere(function ($q) use ($weekOfMonth) {
                            $q->where('mjp.frequency_type', 'biweekly_even')
                                ->whereRaw('? % 2 = 0', [$weekOfMonth]);
                        })
                        ->orWhere(function ($q) use ($weekOfMonth) {
                            $q->where('mjp.frequency_type', 'monthly')
                                ->where('mjp.week_number', $weekOfMonth);
                        });
                })
                ->get();

            return response()->json([
                'success' => true,
                'date' => $today->toDateString(),
                'week_number' => $weekOfMonth,
                'data' => $routes
            ]);

        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }

    /**
     * Helper untuk menghitung minggu ke berapa dalam satu bulan
     */
    private function getWeekOfMonth($date)
    {
        return ceil($date->day / 7);
    }
    
    /**
     * Simpan Check-In Salesman (API dari Android/Flutter)
     */
    public function storeCheckIn(Request $request)
    {
        $request->validate([
            'customer_id' => 'required|exists:customers,id',
            'visit_category' => 'required|in:scheduled,extra_call',
            'lat' => 'required|numeric',
            'lng' => 'required|numeric',
        ]);

        $user = $request->user();
        $today = Carbon::today()->toDateString();

        // PERBAIKAN ENTERPRISE: Validasi Keamanan API (Mencegah check-in ke toko cabang lain)
        $customer = DB::table('customers')->where('id', $request->customer_id)->first();
        if (!$customer || $customer->branch_id !== $user->branch_id) {
            return response()->json(['success' => false, 'message' => 'Akses ditolak: Toko tidak valid atau berada di luar wilayah cabang Anda.'], 403);
        }

        // Proteksi: Cek apakah sudah pernah check-in di toko yang sama hari ini
        $existing = DB::table('salesman_visits')
            ->where('salesman_id', $user->salesman_id)
            ->where('customer_id', $request->customer_id)
            ->whereDate('visit_date', $today)
            ->exists();

        if ($existing) {
            return response()->json(['success' => false, 'message' => 'Anda sudah check-in di toko ini hari ini.'], 400);
        }

        try {
            $visitId = DB::table('salesman_visits')->insertGetId([
                'salesman_id' => $user->salesman_id,
                'customer_id' => $request->customer_id,
                'visit_date' => $today,
                'visit_category' => $request->visit_category,
                'visit_status' => 'check_in',
                'check_in_time' => Carbon::now(),
                'check_in_lat' => $request->lat,
                'check_in_lng' => $request->lng,
                'created_at' => Carbon::now(),
                'updated_at' => Carbon::now()
            ]);

            return response()->json([
                'success' => true, 
                'visit_id' => $visitId, 
                'message' => 'Berhasil Check-In'
            ]);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }
}