<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\Common_model;

class Attendance extends BaseController
{
    protected $common;
    protected $table = 'attendance';

    // 🔹 OFFICE LOCATION (CHANGE THIS)
    const OFFICE_LAT = 17.247699;     // Example: Hyderabad
    const OFFICE_LNG = 80.152192;
    const OFFICE_RADIUS = 200;        // meters

    public function __construct()
    {
        $this->common = new Common_model();
    }

    /* ================= ATTENDANCE PAGE ================= */
    public function index()
    {
        if (!session()->get('isLoggedIn')) {
            return redirect()->to('/');
        }

        $userId = session()->get('user_id');
        $today  = date('Y-m-d');

        $attendance = $this->common->getData(
            $this->table,
            '*',
            [
                'user_id' => $userId,
                'attendance_date' => $today
            ]
        );

        $data['attendance'] = $attendance[0] ?? null;

        return view('admin/attendance', $data);
    }

    /* ================= PUNCH IN ================= */
    public function punchIn()
    {
        $userId = session()->get('user_id');
        $today  = date('Y-m-d');

        $existing = $this->common->getData(
            $this->table,
            'id',
            [
                'user_id' => $userId,
                'attendance_date' => $today
            ]
        );

        if (!empty($existing)) {
            return redirect()->back()->with('error', 'Already punched in today');
        }

        $lat = $this->request->getPost('latitude');
        $lng = $this->request->getPost('longitude');

        if (!$lat || !$lng) {
            return redirect()->back()->with('error', 'Location permission required');
        }

        $workMode = $this->detectWorkMode($lat, $lng);

        $this->common->insertData($this->table, [
            'user_id' => $userId,
            'attendance_date' => $today,
            'punch_in_time' => date('H:i:s'),
            'work_mode' => $workMode,
            'latitude' => $lat,
            'longitude' => $lng,
            'created_at' => date('Y-m-d H:i:s')
        ]);

        return redirect()->back()->with('success', 'Punch In successful');
    }

    /* ================= PUNCH OUT ================= */
    public function punchOut()
    {
        $userId = session()->get('user_id');
        $today  = date('Y-m-d');

        $attendance = $this->common->getData(
            $this->table,
            '*',
            [
                'user_id' => $userId,
                'attendance_date' => $today
            ]
        );

        if (empty($attendance) || !empty($attendance[0]['punch_out_time'])) {
            return redirect()->back()->with('error', 'Invalid Punch Out');
        }

        $this->common->updateData(
            $this->table,
            [
                'punch_out_time' => date('H:i:s'),
                'updated_at' => date('Y-m-d H:i:s')
            ],
            ['id' => $attendance[0]['id']]
        );

        return redirect()->back()->with('success', 'Punch Out successful');
    }

    /* ================= GPS WORK MODE ================= */
    private function detectWorkMode($lat, $lng)
    {
        $distance = $this->distanceInMeters(
            $lat,
            $lng,
            self::OFFICE_LAT,
            self::OFFICE_LNG
        );

        return ($distance <= self::OFFICE_RADIUS) ? 'Office' : 'WFH';
    }

    /* ================= DISTANCE CALCULATION ================= */
    private function distanceInMeters($lat1, $lon1, $lat2, $lon2)
    {
        $earthRadius = 6371000;

        $dLat = deg2rad($lat2 - $lat1);
        $dLon = deg2rad($lon2 - $lon1);

        $a = sin($dLat / 2) ** 2 +
             cos(deg2rad($lat1)) * cos(deg2rad($lat2)) *
             sin($dLon / 2) ** 2;

        $c = 2 * atan2(sqrt($a), sqrt(1 - $a));

        return $earthRadius * $c;
    }
}
