<?php
header('Content-Type: application/json; charset=utf-8');

// 1) Cargar .env y definir la constante CLIENT_SECRET desde la variable de entorno
require_once __DIR__ . '/../env_loader.php';
define('CLIENT_SECRET', env('ZOOM_WEBHOOK_SECRET'));

// 2) Leer y decodificar el JSON del request
$input = file_get_contents("php://input");
$data  = json_decode($input, true);
if (!$data) {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid JSON']);
    exit;
}

// 3) Log del request (opcional, para debug)
file_put_contents(__DIR__.'/zoom_validation.log', date('c')." [REQUEST] -> ".$input."\n", FILE_APPEND);

/**
 * 4) Validaci��n de endpoint.url_validation
 *    (primer evento que env��a Zoom para confirmar el Webhook)
 */
if (isset($data['event']) && $data['event'] === 'endpoint.url_validation') {
    $plainToken = $data['payload']['plainToken'] ?? '';
    if (!$plainToken) {
        http_response_code(400);
        echo json_encode(['error' => 'Missing plainToken']);
        exit;
    }
    // Zoom requiere que devolvamos un encryptedToken generado con HMAC SHA256
    $encryptedToken = hash_hmac('sha256', $plainToken, CLIENT_SECRET, false);
    $responseData = [
        'plainToken'     => $plainToken,
        'encryptedToken' => $encryptedToken
    ];
    file_put_contents(__DIR__.'/zoom_validation.log', date('c')." [RESPONSE] -> ".json_encode($responseData)."\n", FILE_APPEND);
    http_response_code(200);
    echo json_encode($responseData);
    exit;
}

/**
 * 5) meeting.participant_renamed
 *    (cuando un participante cambia su nombre dentro de la reuni��n)
 */
if (isset($data['event']) && $data['event'] === 'meeting.participant_renamed') {
    $participant = $data['payload']['object']['participant'] ?? [];
    $oldUserName = $participant['old_user_name'] ?? '';
    $newUserName = $participant['user_name'] ?? '';

    if ($oldUserName !== '' && $newUserName !== '') {
        $dbname = env("DB_NAME");
        $dbuser = env("DB_USER");
        $dbpass = env("DB_PASS");
        $dbhost = env("DB_HOST");

        try {
            $pdo = new PDO("mysql:host=$dbhost;dbname=$dbname;charset=utf8mb4", $dbuser, $dbpass);
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

            $sql = "UPDATE users
                       SET name = :newName
                     WHERE TRIM(UPPER(name)) = TRIM(UPPER(:oldName))";
            $stmt = $pdo->prepare($sql);
            $stmt->bindParam(':newName', $newUserName, PDO::PARAM_STR);
            $stmt->bindParam(':oldName', $oldUserName, PDO::PARAM_STR);
            $stmt->execute();
            $rowsRenamed = $stmt->rowCount();

            file_put_contents(__DIR__.'/zoom_validation.log',
                date('c')." [INFO] -> Participant renamed from '$oldUserName' to '$newUserName'. Rows updated: $rowsRenamed\n",
                FILE_APPEND
            );
        } catch (PDOException $e) {
            file_put_contents(__DIR__.'/zoom_validation.log',
                date('c')." [ERROR] -> DB error (renamed): ".$e->getMessage()."\n",
                FILE_APPEND
            );
        }
    }
    http_response_code(200);
    echo json_encode(['status' => 'ok', 'action' => 'meeting.participant_renamed processed']);
    exit;
}

/**
 * 6) meeting.participant_joined
 *    (cuando alguien ingresa a la reuni��n)
 */
if (isset($data['event']) && $data['event'] === 'meeting.participant_joined') {
    $participant = $data['payload']['object']['participant'] ?? [];
    // Primero, intentamos usar el registrant_id si se us�� un enlace con registro
    $registrantId = $participant['registrant_id'] ?? '';
    
    if (!empty($registrantId)) {
        // Actualizamos al usuario usando su registrant_id
        $dbname = env("DB_NAME");
        $dbuser = env("DB_USER");
        $dbpass = env("DB_PASS");
        $dbhost = env("DB_HOST");

        try {
            $pdo = new PDO("mysql:host=$dbhost;dbname=$dbname;charset=utf8mb4", $dbuser, $dbpass);
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

            $sql = "UPDATE users
                       SET quorum = 1,
                           fecha_ingreso = NOW(),
                           fecha_salida = NULL
                     WHERE registrozoom = :regId";
            $stmt = $pdo->prepare($sql);
            $stmt->bindParam(':regId', $registrantId, PDO::PARAM_STR);
            $stmt->execute();
            $rowsUpdated = $stmt->rowCount();

            file_put_contents(__DIR__.'/zoom_validation.log',
                date('c')." [INFO] -> Participant joined (by registrant_id: $registrantId). Rows updated: $rowsUpdated\n",
                FILE_APPEND
            );
        } catch (PDOException $e) {
            file_put_contents(__DIR__.'/zoom_validation.log',
                date('c')." [ERROR] -> DB error (joined by registrant_id): ".$e->getMessage()."\n",
                FILE_APPEND
            );
        }
    } else {
        // Si no hay registrant_id, intentamos por user_name
        $zoomName = $participant['user_name'] ?? '';
        if (!empty($zoomName)) {
            $dbname = env("DB_NAME");
        $dbuser = env("DB_USER");
        $dbpass = env("DB_PASS");
        $dbhost = env("DB_HOST");

            try {
                $pdo = new PDO("mysql:host=$dbhost;dbname=$dbname;charset=utf8mb4", $dbuser, $dbpass);
                $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

                $sql = "UPDATE users
                           SET quorum = 1,
                               fecha_ingreso = NOW(),
                               fecha_salida = NULL
                         WHERE TRIM(UPPER(CONCAT(name, ' ', zona))) = TRIM(UPPER(:zoomName))";
                $stmt = $pdo->prepare($sql);
                $stmt->bindParam(':zoomName', $zoomName, PDO::PARAM_STR);
                $stmt->execute();
                $rowsUpdated = $stmt->rowCount();

                file_put_contents(__DIR__.'/zoom_validation.log',
                    date('c')." [INFO] -> Participant joined (by user_name): '$zoomName'. Rows updated: $rowsUpdated\n",
                    FILE_APPEND
                );
            } catch (PDOException $e) {
                file_put_contents(__DIR__.'/zoom_validation.log',
                    date('c')." [ERROR] -> DB error (joined by user_name): ".$e->getMessage()."\n",
                    FILE_APPEND
                );
            }
        }
    }
    http_response_code(200);
    echo json_encode(['status' => 'ok', 'action' => 'meeting.participant_joined processed']);
    exit;
}

/**
 * 7) meeting.participant_left
 *    (cuando alguien sale de la reuni��n)
 */
if (isset($data['event']) && $data['event'] === 'meeting.participant_left') {
    $participant = $data['payload']['object']['participant'] ?? [];
    // Primero, si el evento trae registrant_id, usamos esa clave
    $registrantId = $participant['registrant_id'] ?? '';

    if (!empty($registrantId)) {
        $dbname = env("DB_NAME");
        $dbuser = env("DB_USER");
        $dbpass = env("DB_PASS");
        $dbhost = env("DB_HOST");

        try {
            $pdo = new PDO("mysql:host=$dbhost;dbname=$dbname;charset=utf8mb4", $dbuser, $dbpass);
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

            /* Fix 15B: NULL descuenta inmediato del quorum
               Grace window para votacion se mantiene en PHP controllers */
            $sql = "UPDATE users
                       SET quorum = NULL,
                           fecha_salida = NOW()
                     WHERE registrozoom = :regId";
            $stmt = $pdo->prepare($sql);
            $stmt->bindParam(':regId', $registrantId, PDO::PARAM_STR);
            $stmt->execute();
            $rowsAffected = $stmt->rowCount();

            file_put_contents(__DIR__.'/zoom_validation.log',
                date('c')." [INFO] -> Participant left (by registrant_id: $registrantId). Rows updated: $rowsAffected\n",
                FILE_APPEND
            );
        } catch (PDOException $e) {
            file_put_contents(__DIR__.'/zoom_validation.log',
                date('c')." [ERROR] -> DB error (left by registrant_id): ".$e->getMessage()."\n",
                FILE_APPEND
            );
        }
    } else {
        // Fallback: si no hay registrant_id, buscamos por user_name
        $zoomName = $participant['user_name'] ?? '';
        if (!empty($zoomName)) {
            $dbname = env("DB_NAME");
        $dbuser = env("DB_USER");
        $dbpass = env("DB_PASS");
        $dbhost = env("DB_HOST");

            try {
                $pdo = new PDO("mysql:host=$dbhost;dbname=$dbname;charset=utf8mb4", $dbuser, $dbpass);
                $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

                $sql = "UPDATE users
                           SET quorum = NULL,
                               fecha_salida = NOW()
                         WHERE TRIM(UPPER(CONCAT(name, ' ', zona))) = TRIM(UPPER(:zoomName))";
                $stmt = $pdo->prepare($sql);
                $stmt->bindParam(':zoomName', $zoomName, PDO::PARAM_STR);
                $stmt->execute();
                $rowsAffected = $stmt->rowCount();

                file_put_contents(__DIR__.'/zoom_validation.log',
                    date('c')." [INFO] -> Participant left (by user_name): '$zoomName'. Rows updated: $rowsAffected\n",
                    FILE_APPEND
                );
            } catch (PDOException $e) {
                file_put_contents(__DIR__.'/zoom_validation.log',
                    date('c')." [ERROR] -> DB error (left by user_name): ".$e->getMessage()."\n",
                    FILE_APPEND
                );
            }
        }
    }
    http_response_code(200);
    echo json_encode(['status' => 'ok', 'action' => 'meeting.participant_left processed']);
    exit;
}

/**
 * 8) Respuesta general para cualquier otro evento no contemplado
 */
http_response_code(200);
echo json_encode(['status' => 'ok']);
exit;
