<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Schema;

class SalesmanTargetController extends Controller
{
    /**
     * AMBIL DATA SALESMAN + NAMA (DARI TABEL USERS)
     */
    public function getSalesmenList(Request $request)
    {
        try {
            $user = $request->user();

            $query = DB::table('salesmen as s')
                ->join('users as u', 's.user_id', '=', 'u.id')
                ->select('s.id', 'u.name', 'u.branch_id'); // Tambahkan 'u.branch_id' agar frontend bisa memfilternya

            // PERBAIKAN ENTERPRISE: Isolasi Dropdown Salesman
            // Loloskan owner DAN super_admin agar mereka bisa melihat semua data
            if ($user && !in_array($user->role, ['owner', 'super_admin'])) {
                $query->where('u.branch_id', $user->branch_id);
            }

            $salesmen = $query->get();

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

    /**
     * SIMPAN MASTER TARGET (HEADER & DETAIL)
     * Mendukung flag is_value_target dan is_quantity_target
     */
    public function store(Request $request)
    {
        $request->validate([
            'salesman_id' => 'required',
            'branch_id' => 'required',
            'start_date' => 'required|date',
            'end_date' => 'required|date',
            'target_value_rp' => 'nullable|numeric',
            'is_value_target' => 'nullable|boolean',
            'is_quantity_target' => 'nullable|boolean',
            'items' => 'nullable|array',
        ]);

        $user = $request->user();

        // PERBAIKAN ENTERPRISE: Proteksi Injeksi Cabang
        $branchId = ($user && !in_array($user->role, ['owner', 'super_admin'])) ? $user->branch_id : $request->branch_id;

        // Validasi ekstra: Pastikan salesman yang ditunjuk benar-benar ada di cabang tersebut
        $validSalesman = DB::table('salesmen')
            ->join('users', 'salesmen.user_id', '=', 'users.id')
            ->where('salesmen.id', $request->salesman_id)
            ->where('users.branch_id', $branchId)
            ->exists();

        if (!$validSalesman && !in_array($user->role, ['owner', 'super_admin'])) {
            return response()->json(['success' => false, 'message' => 'Akses Ditolak: Salesman tidak terdaftar di cabang Anda.'], 403);
        }

        try {
            return DB::transaction(function () use ($request, $user, $branchId) {
                // Header (Ada Timestamps & Flag Checkpoint)
                $targetId = DB::table('salesman_targets')->insertGetId([
                    'salesman_id' => $request->salesman_id,
                    'branch_id' => $branchId,
                    'start_date' => $request->start_date,
                    'end_date' => $request->end_date,
                    'is_value_target' => $request->is_value_target ? 1 : 0,
                    'is_quantity_target' => $request->is_quantity_target ? 1 : 0,
                    'target_value_rp' => $request->is_value_target ? ($request->target_value_rp ?? 0) : 0,
                    'notes' => $request->notes,
                    'created_by' => $user->id ?? 1,
                    'created_at' => now(),
                    'updated_at' => now()
                ]);

                // Simpan Detail Quantity hanya jika target quantity dicentang
                if ($request->is_quantity_target && $request->has('items') && count($request->items) > 0) {
                    foreach ($request->items as $item) {
                        DB::table('salesman_target_items')->insert([
                            'target_id' => $targetId,
                            'target_type' => $item['target_type'], 
                            'reference_id' => $item['target_type'] === 'all_product' ? 0 : ($item['reference_id'] ?? 0),
                            'target_qty' => $item['target_qty'],
                            // PERBAIKAN ENTERPRISE: Menghilangkan hardcode fallback 'PCS'
                            'unit' => $item['unit'] ?? '' 
                        ]);
                    }
                }

                return response()->json(['success' => true, 'message' => 'KPI Target Salesman berhasil disimpan.']);
            });
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => "Gagal: " . $e->getMessage()], 500);
        }
    }

    /**
     * ENGINE LAPORAN PENCAPAIAN (LIVE CALCULATION)
     * Menggunakan Filter Dinamis & Logika Pengurang Retur Quantity
     */
    public function getAchievementReport(Request $request)
    {
        try {
            $user = $request->user();
            $targetId = $request->query('target_id');
            if (!$targetId) throw new \Exception("ID Target tidak valid.");

            $target = DB::table('salesman_targets as st')
                ->join('salesmen as s', 'st.salesman_id', '=', 's.id')
                ->join('users as u', 's.user_id', '=', 'u.id')
                ->select('st.*', 'u.name as salesman_name')
                ->where('st.id', $targetId)
                ->first();

            if (!$target) throw new \Exception("Data target tidak ditemukan.");

            // PERBAIKAN ENTERPRISE: Keamanan Mengintip Laporan Cabang Lain
            if ($user && !in_array($user->role, ['owner', 'super_admin']) && $target->branch_id !== $user->branch_id) {
                throw new \Exception("Akses Ditolak: Anda tidak memiliki wewenang untuk melihat KPI cabang ini.");
            }

            $response = [
                'success' => true,
                'header' => [
                    'salesman' => $target->salesman_name,
                    'period' => $target->start_date . ' s/d ' . $target->end_date,
                    'is_value_active' => (bool)$target->is_value_target,
                    'is_qty_active' => (bool)$target->is_quantity_target,
                ],
                'value_data' => null,
                'quantity_data' => []
            ];

            // 1. HITUNG VALUE (Hanya jika is_value_target aktif)
            if ($target->is_value_target) {
                $salesVal = DB::table('sales')
                    ->where('branch_id', $target->branch_id)
                    ->where('delivery_status', '!=', 'void') // Pastikan tidak menghitung faktur batal
                    ->whereExists(function ($query) use ($target) {
                        $query->select(DB::raw(1))->from('customers')
                            ->whereColumn('customers.id', 'sales.customer_id')
                            ->where('customers.salesman_id', $target->salesman_id);
                    })
                    ->whereBetween('created_at', [$target->start_date . ' 00:00:00', $target->end_date . ' 23:59:59'])
                    ->sum(DB::raw('subtotal - discount_amount')); // Mengambil nilai DPP sebelum PPN jika konsepnya Net Revenue

                // Menghitung Retur (Pastikan nama tabel sesuai dengan struktur Sales Return Anda)
                $returnVal = 0;
                if (Schema::hasTable('sale_returns')) {
                    $returnVal = DB::table('sale_returns')
                        ->join('sales', 'sale_returns.sale_id', '=', 'sales.id')
                        ->where('sale_returns.branch_id', $target->branch_id)
                        ->whereExists(function ($query) use ($target) {
                            $query->select(DB::raw(1))->from('customers')
                                ->whereColumn('customers.id', 'sales.customer_id')
                                ->where('customers.salesman_id', $target->salesman_id);
                        })
                        ->whereBetween('sale_returns.created_at', [$target->start_date . ' 00:00:00', $target->end_date . ' 23:59:59'])
                        ->sum('total_refund');
                }

                $netValueActual = (float)$salesVal - (float)$returnVal;

                $response['value_data'] = [
                    'target_rp' => (float)$target->target_value_rp,
                    'actual_rp' => $netValueActual,
                    'percentage_rp' => $target->target_value_rp > 0 ? round(($netValueActual / (float)$target->target_value_rp) * 100, 2) : 0
                ];
            }

            // 2. HITUNG QUANTITY (Hanya jika is_quantity_target aktif)
            if ($target->is_quantity_target) {
                $targetItems = DB::table('salesman_target_items')->where('target_id', $targetId)->get();

                foreach ($targetItems as $ti) {
                    // Query Jual (sale_items)
                    $qSales = DB::table('sale_items as si')
                        ->join('sales as s', 'si.sale_id', '=', 's.id')
                        ->join('customers as c', 's.customer_id', '=', 'c.id')
                        ->join('products as p', 'si.product_id', '=', 'p.id')
                        ->where('s.delivery_status', '!=', 'void')
                        ->where('c.salesman_id', $target->salesman_id)
                        ->whereBetween('s.created_at', [$target->start_date . ' 00:00:00', $target->end_date . ' 23:59:59']);

                    // Query Retur (Jika ada modul retur yang aktif)
                    $totalRetur = 0;
                    if (Schema::hasTable('sale_return_items')) {
                        $qRetur = DB::table('sale_return_items as sri')
                            ->join('sale_returns as sr', 'sri.sale_return_id', '=', 'sr.id')
                            ->join('sales as s', 'sr.sale_id', '=', 's.id')
                            ->join('customers as c', 's.customer_id', '=', 'c.id')
                            ->join('products as p', 'sri.product_id', '=', 'p.id')
                            ->where('c.salesman_id', $target->salesman_id)
                            ->whereBetween('sr.created_at', [$target->start_date . ' 00:00:00', $target->end_date . ' 23:59:59']);
                    }

                    $name = "";
                    if ($ti->target_type === 'product') {
                        $pInfo = DB::table('products')->where('id', $ti->reference_id)->first();
                        $name = $pInfo->name ?? 'Produk';
                        $qSales->where('si.product_id', $ti->reference_id);
                        if (isset($qRetur)) $qRetur->where('sri.product_id', $ti->reference_id);
                    } elseif ($ti->target_type === 'category') {
                        $catInfo = DB::table('categories')->where('id', $ti->reference_id)->first();
                        $name = "KAT: " . ($catInfo->name ?? 'N/A');
                        $qSales->where('p.category_id', $ti->reference_id);
                        if (isset($qRetur)) $qRetur->where('p.category_id', $ti->reference_id);
                    } else {
                        $name = "ALL PRODUCT";
                    }

                    // Kalikan dengan base_conversion_factor agar target selalu mengacu pada satuan terkecil
                    $totalJual = $qSales->sum(DB::raw('si.quantity * COALESCE(si.base_conversion_factor, 1)'));
                    if (isset($qRetur)) {
                        // Sesuaikan field quantity sesuai skema sale_returns
                        $totalRetur = $qRetur->sum('sri.quantity'); 
                    }
                    
                    $actualQtyCalc = (float)$totalJual - (float)$totalRetur;

                    $response['quantity_data'][] = [
                        'name' => $name,
                        'target' => (float)$ti->target_qty,
                        'actual' => round($actualQtyCalc, 2),
                        'unit' => $ti->unit,
                        'percentage' => $ti->target_qty > 0 ? round(($actualQtyCalc / $ti->target_qty) * 100, 2) : 0
                    ];
                }
            }

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

    public function index(Request $request)
    {
        try {
            $user = $request->user();

            $query = DB::table('salesman_targets as t')
                ->join('salesmen as s', 't.salesman_id', '=', 's.id')
                ->join('users as u', 's.user_id', '=', 'u.id')
                ->join('branches as b', 't.branch_id', '=', 'b.id')
                ->select('t.*', 'u.name as salesman_name', 'b.name as branch_name');

            // PERBAIKAN ENTERPRISE: Keamanan Data Lintas Cabang di Daftar List
            if ($user && !in_array($user->role, ['owner', 'super_admin'])) {
                $query->where('t.branch_id', $user->branch_id);
            } else {
                if ($request->branch_id && $request->branch_id !== 'all') {
                    $query->where('t.branch_id', $request->branch_id);
                }
            }

            if ($request->salesman_id) $query->where('t.salesman_id', $request->salesman_id);
            if ($request->start_date) $query->where('t.start_date', '>=', $request->start_date);
            if ($request->end_date) $query->where('t.end_date', '<=', $request->end_date);

            $targets = $query->orderBy('t.created_at', 'desc')->get();

            foreach ($targets as $target) {
                $target->items = DB::table('salesman_target_items as sti')
                    ->leftJoin('products as p', function($join) {
                        $join->on('sti.reference_id', '=', 'p.id')->where('sti.target_type', '=', 'product');
                    })
                    ->leftJoin('categories as c', function($join) {
                        $join->on('sti.reference_id', '=', 'c.id')->where('sti.target_type', '=', 'category');
                    })
                    ->where('sti.target_id', $target->id)
                    ->select('sti.*', 'p.name as product_name', 'c.name as category_name')
                    ->get();
            }

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

    public function update(Request $request, $id)
    {
        $user = $request->user();
        
        if (!in_array($user->role, ['owner', 'super_admin', 'manager'])) {
            return response()->json(['success' => false, 'message' => 'Akses Ditolak! Membutuhkan hak akses Manager/Owner.'], 403);
        }
        if (!Hash::check($request->confirm_password, $user->password)) {
            return response()->json(['success' => false, 'message' => 'Otorisasi Gagal! Password salah.'], 401);
        }

        try {
            DB::transaction(function () use ($request, $id, $user) {
                
                $target = DB::table('salesman_targets')->where('id', $id)->first();
                if (!$target) throw new \Exception('Data target tidak ditemukan.');

                // PERBAIKAN ENTERPRISE: Mencegah Manager mengedit target milik cabang lain
                if (!in_array($user->role, ['owner', 'super_admin']) && $target->branch_id !== $user->branch_id) {
                    throw new \Exception('Akses Ditolak! Target ini bukan wewenang cabang Anda.');
                }

                DB::table('salesman_targets')->where('id', $id)->update([
                    'is_value_target' => $request->is_value_target ? 1 : 0,
                    'is_quantity_target' => $request->is_quantity_target ? 1 : 0,
                    'target_value_rp' => $request->is_value_target ? $request->target_value_rp : 0,
                    'notes' => $request->notes,
                    'updated_at' => now()
                ]);

                DB::table('salesman_target_items')->where('target_id', $id)->delete();
                if ($request->is_quantity_target && $request->has('items') && count($request->items) > 0) {
                    foreach ($request->items as $item) {
                        DB::table('salesman_target_items')->insert([
                            'target_id' => $id,
                            'target_type' => $item['target_type'], 
                            'reference_id' => $item['target_type'] === 'all_product' ? 0 : ($item['reference_id'] ?? 0),
                            'target_qty' => $item['target_qty'],
                            // PERBAIKAN ENTERPRISE: Dinamis tanpa fallback kaku
                            'unit' => $item['unit'] ?? '' 
                        ]);
                    }
                }
            });

            return response()->json(['success' => true, 'message' => 'Data KPI Target berhasil diperbarui.']);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }
}