<?php
// /login/index.php

error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);

// --- CONFIGURACIÓN CORS ---
header("Access-Control-Allow-Origin: http://yaetv.com/panel_api");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
header("Content-Type: application/json; charset=UTF-8");

// --- SESIÓN ---
session_set_cookie_params([
    'lifetime' => 3600,
    'path' => '/',
    'domain' => 'yaetv.com',
    'secure' => true,
    'httponly' => true,
    'samesite' => 'None'
]);
session_start();

// --- ZONA HORARIA ---
date_default_timezone_set('America/Argentina/Mendoza');

// --- DB ---
require_once __DIR__ . '/../con/db_config.php';

function sendJsonResponse($data) {
    echo json_encode($data);
    exit;
}

function logMessage($message) {
    $logfile = '/home/yaetfswo/public_html/panel_api/login/log.txt';
    file_put_contents($logfile, $message . "\n", FILE_APPEND);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $json = file_get_contents('php://input');
    $data = json_decode($json, true) ?? $_POST;

    try {
        $pdo = getDBConnection();

        $usuario = $data['usuario'] ?? '';
        $contrasena = $data['contrasena'] ?? '';
        $deviceID = $data['deviceID'] ?? '';

        if (empty($usuario) || empty($contrasena)) {
            sendJsonResponse(['success' => false, 'message' => 'Correo y contraseña son requeridos']);
        }

        $usuario = filter_var($usuario, FILTER_SANITIZE_EMAIL);

        $stmt = $pdo->prepare("SELECT id, email, password, vencimiento, device_id, device_id_2, device_id_3, device_id_4 FROM users WHERE email = :email");
        $stmt->execute(['email' => $usuario]);
        $user = $stmt->fetch();

        if ($user) {
            if ($contrasena === $user['password']) {
                $hoy = new DateTime();
                $vencimiento = new DateTime($user['vencimiento']);

                logMessage("Fecha de hoy: {$hoy->format('Y-m-d H:i:s')} - Vencimiento: {$vencimiento->format('Y-m-d H:i:s')}");

                if ($vencimiento >= $hoy) {
                    $_SESSION['user_id'] = $user['id'];
                    $_SESSION['email'] = $user['email'];
                    $_SESSION['vencimiento'] = $user['vencimiento'];

                    session_regenerate_id(true);
                    logMessage("PHPSESSID generado: " . session_id());

                    $deviceIDs = array_filter([
                        $user['device_id'],
                        $user['device_id_2'],
                        $user['device_id_3']
                    ], fn($id) => $id !== null && $id !== '');

                    if (in_array($deviceID, $deviceIDs)) {
                        sendJsonResponse([
                            'success' => true,
                            'user' => [
                                'id' => $user['id'],
                                'email' => $user['email'],
                                'vencimiento' => $user['vencimiento']
                            ],
                            'session_status' => 'active'
                        ]);
                    } else {
                        $deviceColumns = ['device_id', 'device_id_2', 'device_id_3'];
                        foreach ($deviceColumns as $column) {
                            if (empty($user[$column])) {
                                $update_stmt = $pdo->prepare("UPDATE users SET $column = :deviceID WHERE id = :id");
                                $update_stmt->execute(['deviceID' => $deviceID, 'id' => $user['id']]);

                                if ($update_stmt->rowCount() > 0) {
                                    sendJsonResponse([
                                        'success' => true,
                                        'user' => [
                                            'id' => $user['id'],
                                            'email' => $user['email'],
                                            'vencimiento' => $user['vencimiento']
                                        ],
                                        'session_status' => 'active'
                                    ]);
                                }
                            }
                        }

                        session_destroy();
                        sendJsonResponse(['success' => false, 'message' => 'No hay más perfiles disponibles para este usuario.']);
                    }
                } else {
                    sendJsonResponse(['success' => false, 'message' => 'Cuenta expirada']);
                }
            } else {
                sendJsonResponse(['success' => false, 'message' => 'Correo electrónico o contraseña incorrectos']);
            }
        } else {
            sendJsonResponse(['success' => false, 'message' => 'Correo electrónico o contraseña incorrectos']);
        }
    } catch (PDOException $e) {
        sendJsonResponse(['success' => false, 'message' => 'Error de servidor: ' . $e->getMessage()]);
    } catch (Exception $e) {
        sendJsonResponse(['success' => false, 'message' => $e->getMessage()]);
    }
} else {
    sendJsonResponse(['success' => false, 'message' => 'Método no permitido']);
}