<?php
include "../../conn.php";
include "../../functions2.php";

header('Content-Type: application/json; charset=utf-8');
header('Strict-Transport-Security: max-age=31536000');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization, AR-REAL-IP');
header('Access-Control-Allow-Credentials: true');

$origin = $_SERVER['HTTP_ORIGIN'] ?? '*';
header('Access-Control-Allow-Origin: ' . $origin);
header('Vary: Origin');

date_default_timezone_set("Asia/Kolkata");
$serviceNowTime = date("Y-m-d H:i:s");

/* ---------------- DEFAULT RESPONSE ---------------- */
$res = [
    'code' => 11,
    'msg' => 'Method not allowed',
    'msgCode' => 12,
    'serviceNowTime' => $serviceNowTime
];

/* ---------------- METHOD CHECK ---------------- */
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode($res);
    exit;
}

/* ---------------- INPUT ---------------- */
$body = json_decode(file_get_contents("php://input"), true);
if (!is_array($body)) {
    echo json_encode([
        'code' => 7,
        'msg' => 'Invalid JSON',
        'msgCode' => 6,
        'serviceNowTime' => $serviceNowTime
    ]);
    exit;
}

/* ---------------- REQUIRED PARAMS ---------------- */
$required = ['language','logintype','phonetype','pwd','random','signature','timestamp','username'];
foreach ($required as $r) {
    if (!isset($body[$r])) {
        echo json_encode([
            'code' => 7,
            'msg' => 'Param is Invalid',
            'msgCode' => 6,
            'serviceNowTime' => $serviceNowTime
        ]);
        exit;
    }
}

/* ---------------- SANITIZE ---------------- */
$language   = trim($body['language']);
$logintype  = trim($body['logintype']);
$phonetype  = trim($body['phonetype']);
$pwd        = trim($body['pwd']);
$random     = trim($body['random']);
$username   = trim($body['username']);
$signature  = strtoupper(trim($body['signature']));
$timestamp  = trim($body['timestamp']);

/* ---------------- SIGNATURE VERIFY (FIXED) ---------------- */
// $signString = $language.$logintype.$phonetype.$pwd.$random.$username;
// $serverSign = strtoupper(md5($signString));

// if ($serverSign !== $signature) {
//     echo json_encode([
//         'code' => 5,
//         'msg' => 'Wrong signature',
//         'msgCode' => 3,
//         'serviceNowTime' => $serviceNowTime
//     ]);
//     exit;
// }

/* ---------------- MOBILE PREFIX FIX ---------------- */
if (substr($username, 0, 2) === "91") {
    $username = substr($username, 2);
}

/* ---------------- USER FETCH ---------------- */
if ($logintype === 'email') {
    $sql = "SELECT id,password,status,ishonup,codechorkamukala,shonupwderr 
            FROM shonu_subjects WHERE email=?";
} else {
    $sql = "SELECT id,password,status,ishonup,codechorkamukala,shonupwderr 
            FROM shonu_subjects WHERE mobile=?";
}

$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $username);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();

if (!$user) {
    echo json_encode([
        'code' => 1,
        'msg' => 'User not exists',
        'msgCode' => 101,
        'serviceNowTime' => $serviceNowTime
    ]);
    exit;
}

/* ---------------- PASSWORD CHECK ---------------- */
if ($user['password'] !== md5($pwd)) {

    $conn->query("UPDATE shonu_subjects SET shonupwderr = shonupwderr + 1 WHERE mobile='$username'");

    echo json_encode([
        'code' => 1,
        'msg' => 'Password does not correct',
        'msgCode' => 117,
        'serviceNowTime' => $serviceNowTime,
        'data' => [
            'tokenHeader' => 'Bearer ',
            'token' => null,
            'expiresIn' => 0,
            'refreshToken' => null,
            'passwordErrorNum' => $user['shonupwderr'] + 1,
            'passwordErrorMaxNum' => 30
        ]
    ]);
    exit;
}

/* ---------------- STATUS CHECK ---------------- */
if ($user['status'] != 1) {
    echo json_encode([
        'code' => 1,
        'msg' => 'User suspended',
        'msgCode' => 116,
        'serviceNowTime' => $serviceNowTime
    ]);
    exit;
}

/* ---------------- TOKEN ---------------- */
$expiresIn = time() + 86400;

$payload = [
    'id' => $user['id'],
    'mobile' => $username,
    'status' => $user['status'],
    'expire' => $expiresIn,
    'ishonup' => $user['ishonup'],
    'codechorkamukala' => $user['codechorkamukala']
];

$token = generate_jwt(['alg'=>'HS256','typ'=>'JWT'], $payload);
$refreshToken = generate_jwt(['alg'=>'HS256','typ'=>'JWT'], [
    'id'=>$user['id'],
    'expire'=>$expiresIn
]);

/* ---------------- IP + UA ---------------- */
$ip = $_SERVER['HTTP_AR_REAL_IP']
    ?? $_SERVER['HTTP_X_FORWARDED_FOR']
    ?? $_SERVER['REMOTE_ADDR']
    ?? 'UNKNOWN';

$ua = $_SERVER['HTTP_USER_AGENT'] ?? '';

$conn->query("
    UPDATE shonu_subjects 
    SET shonupwderr=0,
        ishonup='$ip',
        shonullgnt='$serviceNowTime',
        akshinak='$token',
        tnegaresunohs='".mysqli_real_escape_string($conn,$ua)."'
    WHERE id={$user['id']}
");

/* ---------------- NOTIFICATION ---------------- */
$conn->query("
    INSERT INTO notification (state,title,user_id,created_at)
    VALUES (0,'Login Notification',{$user['id']},'$serviceNowTime')
");

/* ---------------- SUCCESS ---------------- */
echo json_encode([
    'code' => 0,
    'msg' => 'Succeed',
    'msgCode' => 0,
    'serviceNowTime' => $serviceNowTime,
    'data' => [
        'tokenHeader' => 'Bearer ',
        'token' => $token,
        'refreshToken' => $refreshToken,
        'expiresIn' => $expiresIn,
        'passwordErrorNum' => 0,
        'passwordErrorMaxNum' => 30
    ]
]);
