<?php

namespace App\Http\Controllers;

use App\Jobs\LoadHopperJob;
use App\Model\Cron;
use App\Model\User;
use App\Services\ReportService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CronController extends Controller
{

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    private $request;

    public function __construct(Request $request, Cron $cron)
    {
        $this->request = $request;
        $this->model = $cron;
    }

    /*
     * Add records to temp table
     * @return json
     */
    /**
     * @OA\Post(
     *     path="/add-lead-temp",
     *     summary="Add lead to campaign hopper (cron-triggered)",
     *     description="Adds a lead to the hopper if total leads in hopper are less than 30. Typically called by a cron job.",
     *     operationId="addLeadTemp",
     *     tags={"Cron"},
     *     @OA\RequestBody(
     *         required=true,
     *         @OA\JsonContent(
     *             required={"campaign_id", "id"},
     *             @OA\Property(property="campaign_id", type="integer", example=5, description="Campaign ID for which leads are being loaded"),
     *             @OA\Property(property="id", type="integer", example=123, description="Lead ID to be added to the campaign hopper")
     *         )
     *     ),
     *     @OA\Response(
     *         response=201,
     *         description="Lead load request accepted",
     *         @OA\JsonContent(
     *             @OA\Property(property="message", type="string", example="Request accepted")
     *         )
     *     ),
     *     @OA\Response(
     *         response=401,
     *         description="Lead not added due to existing threshold",
     *         @OA\JsonContent(
     *             @OA\Property(property="message", type="string", example="Request declined due to minimum lead is 30")
     *         )
     *     ),
     *     @OA\Response(
     *         response=422,
     *         description="Validation error",
     *         @OA\JsonContent(
     *             @OA\Property(property="message", type="string", example="The given data was invalid."),
     *             @OA\Property(property="errors", type="object",
     *                 @OA\Property(property="campaign_id", type="array", @OA\Items(type="string", example="The campaign_id field is required.")),
     *                 @OA\Property(property="id", type="array", @OA\Items(type="string", example="The id field is required."))
     *             )
     *         )
     *     )
     * )
     */

    public function addLeadTemp(Request $request)
    {
        #Note: this is called from cron so clientId needs to be taken from input
        $this->validate($request, [
            'campaign_id' => 'required|numeric',
            'id' => 'required|numeric'
        ]);
        //$cron = new Cron();
        //$response = $cron->addLeadTemp($request->input('id'), $request->input('campaign_id'));
        //return response()->json($response);

        $getLead = $this->getTempLead($request->input('campaign_id'), $request->input('id'));
        $lead_tempcount = count($getLead);

        if ($lead_tempcount < 30) {
            dispatch(new LoadHopperJob($request->input('id'), $request->input('campaign_id')))->onConnection("database");
            return response("Request accepted", 201);
        } else {
            return response("Request declined due to minimum lead is 30 ", 401);
        }
    }

    public function getTempLead($campaignId, $parentId)
    {
        $leadTemp = DB::connection("mysql_" . $parentId)->select("SELECT * FROM lead_temp WHERE campaign_id = :campaign_id", array('campaign_id' => $campaignId));
        $leadTemp = (array)$leadTemp;
        return $leadTemp;
    }

    public function cronEmail(Request $request)
    {
        $this->validate($request, [
            'email' => 'required|email',
            'clientId' => 'required|int'
        ]);
        $reportService = new ReportService($request->get("clientId"));
        $data = $reportService->dailyCallReport($request->get("email"));
        return view("emails.DailyCallReport.v1")->with([
            "subject" => "Daily Call Report",
            "data" => $data,
        ]);
    }

    /**
     * Email Cron Manager - Start/Stop/Status
     * Usage: /email-cron?action=start|stop|status
     */
    public function emailCronManager(Request $request)
    {
        $action = $request->input('action', 'status');
        $pidFile = storage_path('app/email_cron.pid');
        $scriptPath = base_path('public/cron_fetch_with_webhook.php');

        switch ($action) {
            case 'start':
                return $this->startEmailCron($pidFile, $scriptPath);

            case 'stop':
                return $this->stopEmailCron($pidFile);

            case 'status':
                return $this->emailCronStatus($pidFile);

            default:
                return response()->json([
                    'error' => 'Invalid action',
                    'valid_actions' => ['start', 'stop', 'status']
                ], 400);
        }
    }

    private function startEmailCron($pidFile, $scriptPath)
    {
        // Check if already running
        if (file_exists($pidFile)) {
            $pid = file_get_contents($pidFile);
            if ($this->isProcessRunning($pid)) {
                return response()->json([
                    'status' => 'already_running',
                    'message' => 'Email cron is already running',
                    'pid' => (int)$pid
                ], 200);
            }
        }

        // Get user_email from request (optional parameter)
        $userEmail = request()->input('user_email', 'sr25012002new@gmail.com');

        // Start the script in background with USER_EMAIL environment variable
        $command = sprintf(
            'USER_EMAIL=%s php %s > /dev/null 2>&1 & echo $!',
            escapeshellarg($userEmail),
            escapeshellarg($scriptPath)
        );

        $pid = trim(shell_exec($command));

        // Save PID to file
        file_put_contents($pidFile, $pid);

        return response()->json([
            'status' => 'started',
            'message' => 'Email fetcher script started successfully',
            'pid' => (int)$pid,
            'user_email' => $userEmail,
            'log_file' => 'storage/app/email_fetcher.log',
            'timestamp' => date('Y-m-d H:i:s')
        ], 200);
    }

    private function stopEmailCron($pidFile)
    {
        if (!file_exists($pidFile)) {
            return response()->json([
                'status' => 'not_running',
                'message' => 'No running email cron found'
            ], 200);
        }

        $pid = file_get_contents($pidFile);

        if ($this->isProcessRunning($pid)) {
            // Kill the process
            exec("kill " . escapeshellarg($pid));
            sleep(1); // Wait for process to terminate

            // Verify it stopped
            if (!$this->isProcessRunning($pid)) {
                unlink($pidFile);
                return response()->json([
                    'status' => 'stopped',
                    'message' => 'Email cron stopped successfully',
                    'pid' => (int)$pid
                ], 200);
            } else {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Failed to stop the process',
                    'pid' => (int)$pid
                ], 500);
            }
        } else {
            // Process not running, clean up PID file
            unlink($pidFile);
            return response()->json([
                'status' => 'not_running',
                'message' => 'Process was not running (PID file cleaned up)',
                'pid' => (int)$pid
            ], 200);
        }
    }

    private function emailCronStatus($pidFile)
    {
        if (!file_exists($pidFile)) {
            return response()->json([
                'status' => 'idle',
                'message' => 'Email cron is not running'
            ], 200);
        }

        $pid = file_get_contents($pidFile);

        if ($this->isProcessRunning($pid)) {
            return response()->json([
                'status' => 'running',
                'message' => 'Email cron is currently running',
                'pid' => (int)$pid,
                'log_file' => 'storage/app/email_fetcher.log'
            ], 200);
        } else {
            // Clean up stale PID file
            unlink($pidFile);
            return response()->json([
                'status' => 'idle',
                'message' => 'Email cron is not running (stale PID cleaned up)'
            ], 200);
        }
    }

    private function isProcessRunning($pid)
    {
        if (!$pid) return false;

        // Check if process exists
        $result = shell_exec("ps -p " . escapeshellarg($pid) . " -o pid=");
        return !empty(trim($result));
    }
}
