<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Carbon\Carbon;
use Illuminate\Database\QueryException; // PENAMBAHAN: Untuk menangkap error relasi database

class AdminCompetitorController extends Controller
{
    /**
     * 1. DISPLAY LIST MASTER BRAND KOMPETITOR (UNTUK DATATABLE NEXT.JS)
     */
    public function index(Request $request)
    {
        try {
            // Semua pengguna berhak melihat daftar brand kompetitor
            $brands = DB::table('competitor_brands')
                ->orderBy('brand_name', 'asc')
                ->get();

            return response()->json([
                'success' => true,
                'data' => $brands
            ], 200);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => 'Gagal memuat master brand: ' . $e->getMessage()], 500);
        }
    }

    /**
     * 2. SIMPAN MASTER BRAND KOMPETITOR BARU
     */
    public function store(Request $request)
    {
        $user = $request->user();
        
        // PENAMBAHAN: Proteksi Hak Akses Pusat
        if ($user && $user->role !== 'owner') {
            return response()->json([
                'success' => false, 
                'message' => 'Akses ditolak: Hanya Owner/Pusat yang berhak mengelola Master Brand Kompetitor.'
            ], 403);
        }

        $request->validate([
            'brand_name' => 'required|string|max:100|unique:competitor_brands,brand_name',
            'is_active' => 'required|boolean'
        ]);

        try {
            DB::table('competitor_brands')->insert([
                'brand_name' => strtoupper(trim($request->brand_name)),
                'is_active' => $request->is_active,
                'created_at' => Carbon::now(),
                'updated_at' => Carbon::now()
            ]);

            return response()->json([
                'success' => true,
                'message' => 'Master Brand Kompetitor berhasil ditambahkan!'
            ], 201); 
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => 'Gagal menyimpan brand: ' . $e->getMessage()], 400);
        }
    }

    /**
     * 3. UPDATE MASTER BRAND KOMPETITOR
     */
    public function update(Request $request, $id)
    {
        $user = $request->user();
        
        // PENAMBAHAN: Proteksi Hak Akses Pusat
        if ($user && $user->role !== 'owner') {
            return response()->json([
                'success' => false, 
                'message' => 'Akses ditolak: Hanya Owner/Pusat yang berhak mengubah Master Brand Kompetitor.'
            ], 403);
        }

        $request->validate([
            'brand_name' => 'required|string|max:100|unique:competitor_brands,brand_name,' . $id,
            'is_active' => 'required|boolean'
        ]);

        try {
            $exists = DB::table('competitor_brands')->where('id', $id)->exists();
            if (!$exists) {
                return response()->json(['success' => false, 'message' => 'Data tidak ditemukan.'], 404);
            }

            DB::table('competitor_brands')->where('id', $id)->update([
                'brand_name' => strtoupper(trim($request->brand_name)),
                'is_active' => $request->is_active,
                'updated_at' => Carbon::now()
            ]);

            return response()->json([
                'success' => true,
                'message' => 'Master Brand Kompetitor berhasil diperbarui!'
            ], 200);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => 'Gagal memperbarui brand: ' . $e->getMessage()], 400);
        }
    }

    /**
     * 4. HAPUS MASTER BRAND KOMPETITOR
     */
    public function destroy(Request $request, $id)
    {
        $user = $request->user();
        
        // PENAMBAHAN: Proteksi Hak Akses Pusat
        if ($user && $user->role !== 'owner') {
            return response()->json([
                'success' => false, 
                'message' => 'Akses ditolak: Hanya Owner/Pusat yang berhak menghapus Master Brand Kompetitor.'
            ], 403);
        }

        try {
            $exists = DB::table('competitor_brands')->where('id', $id)->exists();
            if (!$exists) {
                return response()->json(['success' => false, 'message' => 'Data tidak ditemukan.'], 404);
            }

            DB::table('competitor_brands')->where('id', $id)->delete();

            return response()->json([
                'success' => true,
                'message' => 'Master Brand Kompetitor berhasil dihapus dari sistem.'
            ], 200);
        } catch (QueryException $e) {
            // PROTEKSI ENTERPRISE: Tangkap error Foreign Key Constraint
            if ($e->getCode() == "23000") {
                return response()->json([
                    'success' => false, 
                    'message' => 'Gagal menghapus! Data brand ini sudah terikat dengan riwayat nota inteligensi pasar di lapangan. Silakan matikan status aktifnya saja.'
                ], 400);
            }
            return response()->json(['success' => false, 'message' => 'Database Error.'], 500);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }

    /**
     * 5. FUNGSI PENERIMA DARI FLUTTER MOBILE SALESMAN (MENDUKUNG UPLOAD FOTO & MULTIPART KANONIKAL)
     */
    public function storeMarketIntelFromMobile(Request $request)
    {
        $request->validate([
            'salesman_visit_id' => 'required|integer',
            'competitor_brand_id' => 'required|integer',
            'share_of_shelf_percent' => 'required|numeric',
            'competitor_price_found' => 'required|numeric',
            'market_insights_note' => 'nullable|string',
            'competitor_promo_found' => 'nullable|string',
            'shelf_photo' => 'nullable|image|mimes:jpeg,png,jpg|max:5120'
        ]);

        try {
            $user = $request->user();

            // =========================================================================
            // PENAMBAHAN ENTERPRISE: Proteksi IDOR (Insecure Direct Object Reference)
            // Memastikan API Mobile tidak bisa ditembak sembarangan memakai ID kunjungan cabang lain
            // =========================================================================
            $visit = DB::table('salesman_visits')
                ->join('customers', 'salesman_visits.customer_id', '=', 'customers.id')
                ->where('salesman_visits.id', $request->salesman_visit_id)
                ->select('customers.branch_id')
                ->first();

            if (!$visit) {
                return response()->json(['success' => false, 'message' => 'Sesi kunjungan tidak valid.'], 404);
            }

            if ($user->role !== 'owner' && $user->role !== 'manager' && $visit->branch_id !== $user->branch_id) {
                return response()->json([
                    'success' => false, 
                    'message' => 'Akses ditolak (Security Lock): Anda mencoba menyisipkan data ke sesi kunjungan milik cabang lain.'
                ], 403);
            }
            // =========================================================================

            // Handle Upload Foto Etalase Pesaing jika dilampirkan dari mobile
            $photoPath = null;
            if ($request->hasFile('shelf_photo')) {
                $file = $request->file('shelf_photo');
                $photoPath = $file->store('competitors', 'public');
            }

            DB::table('market_intelligences')->insert([
                'salesman_visit_id' => $request->salesman_visit_id,
                'competitor_brand_id' => $request->competitor_brand_id,
                'share_of_shelf_percent' => $request->share_of_shelf_percent,
                'competitor_price_found' => $request->competitor_price_found,
                'shelf_photo_path' => $photoPath,
                'competitor_promo_found' => $request->competitor_promo_found,
                'market_insights_note' => $request->market_insights_note,
                'created_at' => Carbon::now('Asia/Jakarta'),
                'updated_at' => Carbon::now('Asia/Jakarta')
            ]);

            return response()->json([
                'success' => true,
                'message' => 'Aktivitas riset kompetitor & foto lapangan berhasil disimpan!'
            ], 201);

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

    /**
     * 6. DATA REPORTING INTEGRATED: ANALISIS TIM INTEL PASAR (SHARE OF SHELF & PRICING ANALYSIS)
     */
    public function getMarketIntelligenceReport(Request $request)
    {
        $user = $request->user();
        $startDate = $request->query('start_date', Carbon::now()->startOfMonth()->toDateString());
        $endDate = $request->query('end_date', Carbon::now()->endOfMonth()->toDateString());

        // Proteksi Hak Akses Isolasi Laporan Cabang
        $requestedBranchId = $request->query('branch_id', 'all');
        $branchId = ($user && $user->role !== 'owner') ? $user->branch_id : $requestedBranchId;

        try {
            // A. Ambil total rata-rata persentase penguasaan rak (Share of Shelf) per Brand
            $shareOfShelfQuery = DB::table('market_intelligences as mi')
                ->join('competitor_brands as cb', 'mi.competitor_brand_id', '=', 'cb.id')
                ->join('salesman_visits as sv', 'mi.salesman_visit_id', '=', 'sv.id')
                ->join('customers as c', 'sv.customer_id', '=', 'c.id') // Join customer untuk filter cabang
                ->whereBetween('mi.created_at', [$startDate . ' 00:00:00', $endDate . ' 23:59:59'])
                ->select('cb.brand_name', DB::raw('ROUND(AVG(mi.share_of_shelf_percent), 2) as average_share'));

            // Terapkan filter cabang ke agregat Share of Shelf
            if ($branchId !== 'all' && !empty($branchId)) {
                $shareOfShelfQuery->where('c.branch_id', $branchId);
            }

            $shareOfShelfReport = $shareOfShelfQuery->groupBy('cb.id', 'cb.brand_name')
                ->orderBy('average_share', 'desc')
                ->get();

            // B. Ambil perbandingan harga jual temuan kompetitor vs produk internal distributor
            $priceMonitoringQuery = DB::table('market_intelligences as mi')
                ->join('competitor_brands as cb', 'mi.competitor_brand_id', '=', 'cb.id')
                ->join('salesman_visits as sv', 'mi.salesman_visit_id', '=', 'sv.id')
                ->join('customers as c', 'sv.customer_id', '=', 'c.id')
                ->join('users as u', 'sv.salesman_id', '=', 'u.id') 
                ->whereBetween('mi.created_at', [$startDate . ' 00:00:00', $endDate . ' 23:59:59'])
                ->select(
                    'mi.id',
                    'cb.brand_name as competitor_brand',
                    'c.name as customer_name',
                    'u.name as salesman_name',
                    'mi.share_of_shelf_percent',
                    'mi.competitor_price_found',
                    'mi.competitor_promo_found', 
                    'mi.shelf_photo_path',
                    'mi.market_insights_note',
                    'mi.created_at as visit_time'
                );

            // Terapkan filter cabang ke list Log Harga
            if ($branchId !== 'all' && !empty($branchId)) {
                $priceMonitoringQuery->where('c.branch_id', $branchId);
            }

            $priceMonitoringList = $priceMonitoringQuery->orderBy('mi.created_at', 'desc')
                ->get()
                ->map(function($item) {
                    $item->shelf_photo_url = $item->shelf_photo_path ? asset('storage/' . $item->shelf_photo_path) : null;
                    return $item;
                });

            return response()->json([
                'success' => true,
                'filters' => ['start_date' => $startDate, 'end_date' => $endDate, 'branch_id' => $branchId],
                'share_of_shelf_summary' => $shareOfShelfReport,
                'detail_logs' => $priceMonitoringList
            ], 200);

        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => 'Gagal memuat rekap analisis intel pasar: ' . $e->getMessage()], 500);
        }
    }
}