<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

class PartnerController extends Controller
{
    
    public function handleZohoCallback(Request $request)
{
    $code = $request->code;

    if (!$code) {
        return "No code received";
    }

    $response = Http::asForm()->post('https://accounts.zoho.in/oauth/v2/token', [
        'grant_type' => 'authorization_code',
        'client_id' => env('ZOHO_CLIENT_ID'),
        'client_secret' => env('ZOHO_CLIENT_SECRET'),
        'redirect_uri' => 'https://jitreal.xyz/zoho/callback', // ✅ fixed
        'code' => $code,
    ]);

    $data = $response->json();

    if (!isset($data['refresh_token'])) {
        dd('Zoho Callback Error: ' . json_encode($data));
    }

    // Save refresh token
    file_put_contents(
        base_path('.env'),
        preg_replace(
            '/ZOHO_REFRESH_TOKEN=.*/',
            'ZOHO_REFRESH_TOKEN=' . $data['refresh_token'],
            file_get_contents(base_path('.env'))
        )
    );

    dd('Zoho Refresh Token Saved');
}
public function redirectToZoho()
{
    $url = "https://accounts.zoho.in/oauth/v2/auth?" . http_build_query([
        'scope' => 'ZohoCRM.modules.ALL',
        'client_id' => env('ZOHO_CLIENT_ID'),
        'response_type' => 'code',
        'access_type' => 'offline',
        'redirect_uri' => 'https://jitreal.xyz/zoho/callback',
    ]);

    return redirect($url);
}
    public function create()
    {
        return view('partner.register');
    }

    // ===============================
    // REGISTER PARTNER
    // ===============================
public function store(Request $request)
{
    $request->validate([
        'full_name' => 'required',
        'mobile' => 'required|unique:partners,mobile',
        'email' => 'required|email|unique:partners,email',
    ]);

    // Generate IDs
    $partnerId = 'PARTNER-' . date('Y') . '-' . strtoupper(Str::random(6));
    $referralCode = 'IGS' . strtoupper(Str::random(3));

    $mobile = '91' . preg_replace('/[^0-9]/', '', $request->mobile);

    // Links
    $whatsappLink = 'https://wa.me/' . $mobile . '?text=' . $referralCode;
    $landingPage = url('/partner/' . strtolower($referralCode));

    // Save
    DB::table('partners')->insert([
        'partner_id' => $partnerId,
        'referral_code' => $referralCode,
        'full_name' => $request->full_name,
        'mobile' => $request->mobile,
        'email' => $request->email,
        'whatsapp_link' => $whatsappLink,
        'landing_page' => $landingPage,
        'city' => $request->city,
        'occupation' => $request->occupation,
        'aadhaar_pan' => encrypt($request->aadhaar_pan),
        'bank_details' => encrypt($request->bank_details),
        'social_link' => $request->social_link,
        'created_at' => now(),
        'updated_at' => now(),
    ]);

    // Zoho
    try {
        $this->sendToZoho($request, $referralCode);
    } catch (\Exception $e) {
        Log::error('Zoho Error: ' . $e->getMessage());
    }

    // ✅ WhatsApp (DIRECT, NO ZAPIER)
    try {
       $link = $this->sendWhatsApp(
    $mobile,
    "Welcome {$request->full_name}! 🎉\nYour Referral Code: {$referralCode}\nStart sharing and earn."


        );
    } catch (\Exception $e) {
        Log::error('WhatsApp Error: ' . $e->getMessage());
    }

return back()->with([
    'success' => 'Registered Successfully!',
    'whatsapp_link' => $link
]);}

private function createWhatsAppLink($phone, $message)
{
    $phone = '91' . preg_replace('/[^0-9]/', '', $phone);
    return "https://wa.me/{$phone}?text=" . urlencode($message);
}
private function partnerOnboardingMessage($name, $referralCode)
{
    return "Welcome {$name} 🎉\n\n"
        . "Your Referral Code: {$referralCode}\n\n"
        . "Start sharing & earning 💰\n"
        . "Share this link with students.";
}
public function studentWhatsAppEntry($referralCode)
{
    $message = "Hi, I am interested in studying abroad 🎓\n\n"
        . "Referral Code: {$referralCode}\n\n"
        . "Please share details:\n"
        . "Preferred Country:\n"
        . "Budget:\n"
        . "IELTS/PTE:\n"
        . "Qualification:\n"
        . "Passport Available:\n"
        . "Intake:\n";

    return redirect($this->createWhatsAppLink('91XXXXXXXXXX', $message));
}
public function submitLead(Request $request)
{
    $referralCode = session('referral_code');

    $partner = DB::table('partners')
        ->where('referral_code', $referralCode)
        ->first();

    $counselor = $this->assignCounselor();

    $leadId = DB::table('leads')->insertGetId([
        'counselor_id' => $counselor->id ?? null,
        'name' => $request->name,
        'phone' => $request->phone,
        'email' => $request->email,
        'country' => $request->country,
        'intake' => $request->intake,
        'documents_status' => 'Not Started',
        'stage' => 'New Lead',
        'referral_code' => $referralCode,
        'partner_id' => $partner->id ?? null,
        'source' => $partner ? 'partner' : 'direct',
        'created_at' => now(),
        'updated_at' => now(),
    ]);

    // ✅ Zoho Lead
    $this->sendLeadToZoho($request, $referralCode);

$zohoLeadId = $zohoResponse['data'][0]['details']['id'] ?? null;
$zohoDealId = null;

// ✅ CREATE DEAL ONLY ONCE
if ($zohoLeadId) {
    $dealResponse = $this->createZohoDeal($zohoLeadId, $request);
    $zohoDealId = $dealResponse['data'][0]['details']['id'] ?? null;
}

DB::table('leads')->where('id', $leadId)->update([
    'zoho_lead_id' => $zohoLeadId,
    'zoho_deal_id' => $zohoDealId
]);
    $message = "New Student Lead 🚀\n\n"
        . "Name: {$request->name}\n"
        . "Phone: {$request->phone}\n"
        . "Country: {$request->country}\n"
        . "Intake: {$request->intake}\n";

    return redirect($this->createWhatsAppLink($request->phone, $message));
}
 private function sendWhatsApp($phone, $message)
{
    // ✅ Clean phone
    $phone = '91' . preg_replace('/[^0-9]/', '', $phone);

    // ✅ Encode message
    $encodedMessage = urlencode($message);

    // ✅ Create WhatsApp link
    $whatsappLink = "https://wa.me/{$phone}?text={$encodedMessage}";

    return $whatsappLink;
}
   
   
   
  public function dashboard()
{
    return view('admin.dashboard', [
        'totalLeads' => DB::table('leads')->count(),
        'visaApproved' => DB::table('leads')->where('stage','Visa Approved')->count(),
        'pending' => DB::table('leads')->count()
    ]);
}

public function viewLead($id)
{
    $lead = DB::table('leads')->where('id', $id)->first();
    return view('admin.lead-detail', compact('lead'));
}

public function counselorList()
{
    $counselors = DB::table('counselors')->get();
    return view('admin.counselors', compact('counselors'));
}
    public function landing($code)
    {
        $partner = DB::table('partners')
            ->where('referral_code', strtoupper($code))
            ->first();

        if (!$partner) {
            abort(404);
        }

        // Save referral in session
        session(['referral_code' => $partner->referral_code]);
$counselors = DB::table('counselors')->where('active', 1)->get();

        return view('landing.page', compact('partner', 'counselors'));
    }
public function createCounselor()
{
    return view('admin.add-counselor');
}

public function storeCounselor(Request $request)
{
    DB::table('counselors')->insert([
        'name' => $request->name,
        'active' => 1,
        'assigned_count' => 0,
        'created_at' => now(),
        'updated_at' => now(),
    ]);

    return back()->with('success', 'Counselor Added');
}
  private function assignCounselor()
{
    return DB::table('counselors')
        ->where('active', 1)
        ->orderBy('assigned_count', 'asc')
        ->first();
}

public function counselorWhatsApp($leadId)
{
    $lead = DB::table('leads')->where('id', $leadId)->first();
    $counselor = DB::table('counselors')->where('id', $lead->counselor_id)->first();

    $message = "New Lead Assigned 👇\n\n"
        . "Name: {$lead->name}\n"
        . "Phone: {$lead->phone}\n"
        . "Country: {$lead->country}\n";

    return redirect($this->createWhatsAppLink($counselor->phone, $message));
}
public function bookAppointment($leadId)
{
    $lead = DB::table('leads')->where('id', $leadId)->first();

    $message = "📅 Book Your Counseling Session\n\n"
        . "Click here to book: https://yourwebsite.com/book\n";

    return redirect($this->createWhatsAppLink($lead->phone, $message));
}
public function nurtureLead($leadId)
{
    $lead = DB::table('leads')->where('id', $leadId)->first();

    $message = "Hi {$lead->name} 😊\n\n"
        . "We have great options for your profile.\n"
        . "Let's explore together.";

    return redirect($this->createWhatsAppLink($lead->phone, $message));
}
public function sendBrochure($leadId)
{
    $lead = DB::table('leads')->where('id', $leadId)->first();

    $message = "📘 {$lead->country} Study Guide\n\n"
        . "Download here: https://yourwebsite.com/brochures/{$lead->country}.pdf";

    return redirect($this->createWhatsAppLink($lead->phone, $message));
}
private function detectLeadType($request)
{
    if ($request->budget >= 1500000 && $request->ielts >= 6) {
        return 'hot';
    }
    return 'cold';
}
public function partnerPerformance($partnerId)
{
    $partner = DB::table('partners')->where('id', $partnerId)->first();

    $totalLeads = DB::table('leads')
        ->where('partner_id', $partnerId)
        ->count();

    $message = "📊 Your Performance\n\n"
        . "Total Leads: {$totalLeads}\n"
        . "Keep growing 🚀";

    return redirect($this->createWhatsAppLink($partner->mobile, $message));
}
public function sendMarketingToPartner($partnerId)
{
    $partner = DB::table('partners')->where('id', $partnerId)->first();

    $message = "🔥 Daily Update\n\n"
        . "New universities open for intake.\n"
        . "Start promoting now 🚀";

    return redirect($this->createWhatsAppLink($partner->mobile, $message));
}
private function autoUpdateStage($lead)
{
    if (!$lead->zoho_deal_id) return;

    $map = [
        "Not Started" => "New Lead",
        "Contacted" => "Contacted",
        "Interested" => "Interested",
        "Uploaded" => "Documents Pending",
        "Verified" => "Application Started",
        "Offer Received" => "Offer Letter",
        "Visa Filed" => "Visa Filed",
        "Visa Approved" => "Visa Approved",
    ];

    if (isset($map[$lead->documents_status])) {

        $stage = $map[$lead->documents_status];

        $this->updateDealStage($lead->zoho_deal_id, $stage);

        DB::table('leads')->where('id', $lead->id)->update([
            'stage' => $stage
        ]);
    }
}
public function updateDealStage($dealId, $stage)
{
    $token = $this->getZohoAccessToken();

    Http::withToken($token)->put(
        'https://www.zohoapis.in/crm/v2/Deals',
        [
            "data" => [[
                "id" => $dealId,
                "Stage" => $stage
            ]]
        ]
    );
}
private function createZohoDeal($leadId, $request)
{
$token = $this->getZohoAccessToken();

$response = Http::withToken($token)->post(
    'https://www.zohoapis.in/crm/v2/Deals',
    [
        "data" => [[
            "Deal_Name" => $request->name . " - Application",

            // ✅ FIXED PIPELINE
            "Pipeline" => "Student Journey",
            "Stage" => "New Lead",

            "Closing_Date" => now()->addDays(30)->toDateString(),

            "Account_Name" => [
                "name" => $request->name
            ],

            "Phone" => $request->phone,
            "Description" => "Lead ID: " . $leadId
        ]]
    ]
);

return $response->json();

}

public function updateLeadData(Request $request, $id)
{
    $lead = DB::table('leads')->where('id', $id)->first();

    if (!$lead) {
        return "Lead not found";
    }

    // ✅ UPDATE DATABASE
    DB::table('leads')->where('id', $id)->update([
        'documents_status' => $request->documents_status,
        'updated_at' => now()
    ]);

    // GET UPDATED DATA
    $lead = DB::table('leads')->where('id', $id)->first();

    // 🔥 AUTO STAGE (NO BUTTON)
    $this->autoUpdateStage($lead);

    return "Updated Successfully";
}

public function zohoWebhook(Request $request)
{
    \Log::info('Webhook Hit:', $request->all());

    $dealId = $request->input('id');
    $stage = $request->input('Stage');
    $mobile = $request->input('Phone'); // ✅ DIRECT FROM WEBHOOK

    if (!$dealId) {
        return response()->json(['error' => 'No Deal ID']);
    }

    if (!$mobile) {
        \Log::error('Mobile not received in webhook');
    }

    // 🔥 ACTIONS
    if ($stage == "Interested") {
        $this->sendStageWhatsApp($mobile, "Interested");
    }

    if ($stage == "Visa Approved") {
        $this->addCommission($dealId);
        $this->sendStageWhatsApp($mobile, "Visa Approved");
    }

    return response()->json(['status' => 'success']);
}
private function sendStageWhatsApp($phone, $stage)
{
    // ✅ CLEAN PHONE (India format)
    $phone = '91' . preg_replace('/[^0-9]/', '', $phone);

    // ✅ STAGE MESSAGES
    $messages = [
        "Documents Pending" => "Please upload your documents to continue your application.",
        "Application Started" => "Your application process has started successfully.",
        "Offer Letter" => "🎉 Congratulations! Your offer letter has been received.",
        "Visa Filed" => "Your visa application has been filed successfully.",
    ];

    $message = $messages[$stage] ?? "Your application status has been updated.";

    // 🔥 WHATSAPP CLOUD API CALL
    $response = Http::withToken(env('EAF5SOfQGISMBRosZA2ZCwl9VciACgspFbJ839Ehnumw6iKmnejhrZBhWzVYqKLYq2WZAOnyi8mW4tyPNgUXYhOCfFpprN1X88Mt0hOj0ZAxAsmAihM4nnoS6pLJoVn8umM8Ysxqpxl2vZCSn3iR9AchfUPrPEDhlupo4eqWEZCxpquW6QdpsFdQhncYl6dFRgnVocgtYpZClzX2evwPZCehyqPOVzyAqtr9GYp4lR67aL88s4jvcvfRfRqgjQQzr74eWVBEcAlyPRxMElCv5hcWD6'))->post(
        'https://graph.facebook.com/v19.0/' . env('1148116155049064') . '/messages',
        [
            "messaging_product" => "whatsapp",
            "to" => $phone,
            "type" => "text",
            "text" => [
                "body" => $message
            ]
        ]
    );

    return $response->json();
}


    // ===============================
    // ZOHO TOKEN
    // ===============================
public function generateZohoToken(Request $request)
{
    $code = $request->code;
    if (!$code) {
        return "No code received";
    }

    $response = Http::asForm()->post('https://accounts.zoho.in/oauth/v2/token', [
        'grant_type' => 'authorization_code',
        'client_id' => env('ZOHO_CLIENT_ID'),
        'client_secret' => env('ZOHO_CLIENT_SECRET'),
        'redirect_uri' => 'https://jitreal.xyz/zoho',
        'code' => $code,
    ]);

    $data = $response->json();

    if (!isset($data['refresh_token'])) {
        return response()->json($data);
    }

    // ðŸ”¥ SAVE refresh token automatically
    file_put_contents(
        base_path('.env'),
        preg_replace(
            '/ZOHO_REFRESH_TOKEN=.*/',
            'ZOHO_REFRESH_TOKEN=' . $data['refresh_token'],
            file_get_contents(base_path('.env'))
        )
    );

    return "âœ… Refresh Token Saved Successfully!";
}
private function getZohoAccessToken()
{
    $response = Http::asForm()->post('https://accounts.zoho.in/oauth/v2/token', [
        'refresh_token' => env('ZOHO_REFRESH_TOKEN'),
        'client_id' => env('ZOHO_CLIENT_ID'),
        'client_secret' => env('ZOHO_CLIENT_SECRET'),
        'grant_type' => 'refresh_token',
    ]);

    $data = $response->json();

    if (!isset($data['access_token'])) {
        dd('Zoho Token Error: ' . json_encode($data));
        throw new \Exception('Token not received');
    }

    return $data['access_token'];
}

    // ===============================
    // SEND PARTNER TO ZOHO
    // ===============================
    private function sendToZoho($request, $referralCode)
    {
        $token = $this->getZohoAccessToken();

        Http::withToken($token)->post('https://www.zohoapis.in/crm/v2/Leads', [
            "data" => [
                [
                    "Company" => "Partner",
                    "Last_Name" => $request->full_name,
                    "Phone" => $request->mobile,
                    "Email" => $request->email,
                    "City" => $request->city,
                    "Description" => "Referral Code: " . $referralCode
                ]
            ]
        ]);
    }

/* private function createZohoDeal($leadId, $request)
{
    $token = $this->getZohoAccessToken();

    $response = Http::withToken($token)->post(
        'https://www.zohoapis.in/crm/v2/Deals',
        [
            "data" => [[
                "Deal_Name" => $request->name . " - Application",

                // 🔥 PIPELINE
                "Pipeline" => "Student Journey",
                "Stage" => "New Lead",

                // 🔗 LINK WITH LEAD
                "Lead_Id" => $leadId,

                "Closing_Date" => now()->addMonths(3)->toDateString(),
            ]]
        ]
    );

    return $response->json();
}*/
  private function sendLeadToZoho($request, $referralCode)
{
    $token = $this->getZohoAccessToken();

  $response=  Http::withToken($token)->post('https://www.zohoapis.in/crm/v2/Leads', [
        "data" => [[
            "Company" => "Lead",
            "Last_Name" => $request->name,
            "Phone" => $request->phone,
            "Email" => $request->email,

            // 🔥 CRM FIELDS
            "Country_Preference" => $request->country,
            "Intake" => $request->intake,
            "Documents_Status" => "Not Started",

            "Description" => "Referral Code: " . $referralCode
        ]]
    ]);
   
   
    return $response->json();
    
  
}
public function leadList()
{
    $leads = DB::table('leads')->orderBy('id', 'desc')->get();
    return view('admin.leads', compact('leads'));
}
    // ===============================
    // ZAPIER
    // ===============================
    private function triggerZapier($request, $referralCode, $partnerId)
    {
        $mobile = '91' . preg_replace('/[^0-9]/', '', $request->mobile);

        $message = "Hi {$request->full_name}, Welcome! Code: {$referralCode}";

        Http::post('https://hooks.zapier.com/hooks/catch/27744488/4oja2l0/', [
            'name' => $request->full_name,
            'phone' => $mobile,
            'referral_code' => $referralCode,
            'partner_id' => $partnerId,
            'whatsapp_link' => 'https://wa.me/' . $mobile . '?text=' . urlencode($message),
        ]);
    }
}