<?php

http_response_code(200);

$rawBody = file_get_contents("php://input");
$data = json_decode($rawBody, true);

file_put_contents(
    __DIR__ . "/webhook_mp_log.txt",
    print_r([
        "fecha" => date("Y-m-d H:i:s"),
        "method" => $_SERVER['REQUEST_METHOD'],
        "get" => $_GET,
        "body" => $data,
        "raw_body" => $rawBody
    ], true) . "\n----------------------\n",
    FILE_APPEND
);

$topic = $_GET['topic'] ?? $_GET['type'] ?? ($data['type'] ?? $data['topic'] ?? '');

if ($topic != 'payment') {
    echo "OK";
    exit;
}

$payment_id = null;

if (isset($data['data']['id'])) {
    $payment_id = $data['data']['id'];
} elseif (isset($_GET['data_id'])) {
    $payment_id = $_GET['data_id'];
} elseif (isset($_GET['id'])) {
    $payment_id = $_GET['id'];
} elseif (isset($data['resource']) && is_numeric($data['resource'])) {
    $payment_id = $data['resource'];
}

if (!$payment_id) {
    echo "OK";
    exit;
}

$bd = isset($_GET['bd']) ? trim($_GET['bd']) : '';
$suc = isset($_GET['suc']) ? trim($_GET['suc']) : '';

if ($bd == '' || $suc == '') {
    echo "OK";
    exit;
}

$opBD = explode("_", $bd);
$bdC = $opBD[1] ?? $bd;

$connCentral = new mysqli("directoriofitness.com.mx", "direct18", "L4LL4v3M@3str@", "direct18_ProGymCloud");
$connCentral->set_charset("utf8");

$queryApi = "SELECT info_mercadopago.*
             FROM info_mercadopago
             INNER JOIN gimnasios 
                ON info_mercadopago.gimnasio_idGimnasio = gimnasios.idGimnasio
             WHERE gimnasios.BaseDatos = '$bdC'
             AND info_mercadopago.sucursal_idSucursal = '$suc'
             LIMIT 1";

$resultApi = $connCentral->query($queryApi);

if (!$resultApi || $resultApi->num_rows == 0) {
    $connCentral->close();
    echo "OK";
    exit;
}

$row = $resultApi->fetch_assoc();
$ACCESS_TOKEN = $row['access_token'];
$connCentral->close();

$conn = new mysqli("directoriofitness.com.mx", "direct18", "L4LL4v3M@3str@", $bd);
$conn->set_charset("utf8");

if ($conn->connect_error) {
    file_put_contents(
        __DIR__ . "/payment_detail_log.txt",
        "ERROR CONEXION BD GYM bd=$bd error=" . $conn->connect_error . "\n----------------------\n",
        FILE_APPEND
    );
    echo "OK";
    exit;
}

$ch = curl_init("https://api.mercadopago.com/v1/payments/" . $payment_id);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Authorization: Bearer " . $ACCESS_TOKEN
]);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$errorCurl = curl_error($ch);

curl_close($ch);

$payment = json_decode($response, true);

file_put_contents(
    __DIR__ . "/payment_detail_log.txt",
    print_r([
        "fecha" => date("Y-m-d H:i:s"),
        "payment_id" => $payment_id,
        "bd" => $bd,
        "bdC" => $bdC,
        "suc" => $suc,
        "http_code" => $httpCode,
        "curl_error" => $errorCurl,
        "payment_response" => $payment
    ], true) . "\n----------------------\n",
    FILE_APPEND
);

if ($httpCode < 200 || $httpCode >= 300 || !isset($payment['status'])) {
    $conn->close();
    echo "OK";
    exit;
}

$status = $payment['status'];
$status_detail = $payment['status_detail'] ?? '';
$external_reference = $payment['external_reference'] ?? '';
$transaction_amount = $payment['transaction_amount'] ?? 0;
$payer_email = $payment['payer']['email'] ?? '';
$raw_response = json_encode($payment, JSON_UNESCAPED_UNICODE);
$metadata = $payment['metadata'] ?? [];

$id_cliente = $metadata['id_cliente'] ?? 0;
$tipo = $metadata['tipo'] ?? '';
$id_servicio = $metadata['id_servicio'] ?? null;
$costo = $metadata['importe'] ?? $transaction_amount;
$plan = 4;
$fecha_visita = $metadata['fecha_visita'] ?? '';
$paquete_clase = $metadata['paquete_clase'] ?? '';
$opcion = $metadata['opcion'] ?? '';
$concepto = $metadata['concepto'] ?? '';
$idLocker = $metadata['id_locker'] ?? '';
$lock_asig = $metadata['lock_asig'] ?? '';

$payment_id_safe = $conn->real_escape_string($payment_id);
$external_reference_safe = $conn->real_escape_string($external_reference);
$status_safe = $conn->real_escape_string($status);
$status_detail_safe = $conn->real_escape_string($status_detail);
$payer_email_safe = $conn->real_escape_string($payer_email);
$bd_safe = $conn->real_escape_string($bd);
$bdC_safe = $conn->real_escape_string($bdC);
$raw_response_safe = $conn->real_escape_string($raw_response);
$tipo_safe = $conn->real_escape_string($tipo);

$suc_safe = (int)$suc;
$id_cliente_safe = (int)$id_cliente;
$amount_safe = (float)$transaction_amount;

$queryInsertWebhook = "
    INSERT INTO pagos_mercadopago_webhook
    (
        payment_id,
        external_reference,
        status,
        status_detail,
        transaction_amount,
        payer_email,
        bd,
        bdC,
        sucursal_id,
        tipo,
        id_cliente,
        procesado,
        mensaje,
        raw_response
    )
    VALUES
    (
        '$payment_id_safe',
        '$external_reference_safe',
        '$status_safe',
        '$status_detail_safe',
        $amount_safe,
        '$payer_email_safe',
        '$bd_safe',
        '$bdC_safe',
        $suc_safe,
        '$tipo_safe',
        $id_cliente_safe,
        0,
        'RECIBIDO',
        '$raw_response_safe'
    )
";

if (!$conn->query($queryInsertWebhook)) {
    file_put_contents(
        __DIR__ . "/payment_detail_log.txt",
        "PAGO DUPLICADO O ERROR INSERT WEBHOOK payment_id=$payment_id error=" . $conn->error . "\n----------------------\n",
        FILE_APPEND
    );

    $conn->close();
    echo "OK";
    exit;
}

if ($status != "approved") {
    $statusMsg = $conn->real_escape_string("PAGO NO APROBADO: " . $status . " - " . $status_detail);

    $conn->query("
        UPDATE pagos_mercadopago_webhook
        SET mensaje = '$statusMsg'
        WHERE payment_id = '$payment_id_safe'
        LIMIT 1
    ");

    $conn->close();
    echo "OK";
    exit;
}

$msgProceso = "";

if ($tipo == 'planes') {

    $id_servicio = (int)$id_servicio;
    $id_cliente = (int)$id_cliente;
    $costo = (float)$costo;
    $plan = (int)$plan;
    $suc = (int)$suc;

    $query_fecha = "SELECT * FROM (
        SELECT 
            socio_servicio.idServicio AS id,
            pagos.FechaInicio,
            servicios.NombreServicio,
            socio_servicio.idSocio_Servicio AS idss,
            socio_servicio.idSocioTitular AS st,
            pagos.FechaFin
        FROM socio_servicio
        INNER JOIN pagos
            ON socio_servicio.idSocio_Servicio = pagos.idSocio_Servicio
        INNER JOIN servicios
            ON socio_servicio.idServicio = servicios.idServicio
        INNER JOIN socios
            ON socio_servicio.idSocio = socios.idSocio
        WHERE socio_servicio.idSocio = '$id_cliente'
        AND pagos.Cancelado = 0
        AND pagos.Visible = 1
        AND servicios.idServicio = '$id_servicio'
        GROUP BY socio_servicio.idSocio_Servicio DESC
    ) AS tmp
    GROUP BY tmp.id
    ORDER BY tmp.idss DESC";

    $result_fecha = $conn->query($query_fecha);

    $row_fecha = null;
    if ($result_fecha && $result_fecha->num_rows > 0) {
        $row_fecha = $result_fecha->fetch_assoc();
    }

    if ($opcion == '97' && $row_fecha) {
        $idP = $row_fecha['id'];
        $query = "INSERT INTO socio_servicio(idServicio,idSocio,idSocioTitular,FechaSolicitud,FechaInscripcion)
                  VALUES('$idP','$id_cliente','$id_cliente',CURDATE(),CURDATE())";
    } else {
        $query = "INSERT INTO socio_servicio(idServicio,idSocio,idSocioTitular,FechaSolicitud,FechaInscripcion)
                  VALUES('$id_servicio','$id_cliente','$id_cliente',CURDATE(),CURDATE())";
    }

    if ($conn->query($query) == TRUE) {

        $id_insert = $conn->insert_id;
        $mes = 0;
        $conceptoPago = 0;

        switch($plan){
            case 1: $mes = 0; $conceptoPago = 0; break;
            case 2: $mes = 7; $conceptoPago = 1; break;
            case 3: $mes = 15; $conceptoPago = 2; break;
            case 4: $mes = 1; $conceptoPago = 3; break;
            case 5: $mes = 2; $conceptoPago = 4; break;
            case 6: $mes = 3; $conceptoPago = 5; break;
            case 7: $mes = 4; $conceptoPago = 6; break;
            case 8: $mes = 6; $conceptoPago = 7; break;
            case 9: $mes = 12; $conceptoPago = 8; break;
            default: $mes = 0; $conceptoPago = 0; break;
        }

        $fechaI = date('Y-m-d');

        if ($row_fecha) {
            $fechaI = $row_fecha['FechaFin'];
        }

        if($opcion == "99"){
            $conceptoPago = "99";
            $visible = '1';
        } else if($opcion == "97"){
            $fechaI = date('Y-m-d');
            $conceptoPago = "97";
            $visible = '1';
        } else {
            $visible = '1';
        }

        if($mes == 0 || $mes == 7 || $mes == 15){
            $fecha_vencimiento = "DATE_ADD('$fechaI', INTERVAL ".$mes." DAY)";
        }else{
            $fecha_vencimiento = "DATE_ADD('$fechaI', INTERVAL ".$mes." MONTH)";
        }

        $query_pagos = "INSERT INTO pagos (
            idSocio_Servicio,
            Concepto,
            FechaPago,
            Importe,
            idUsuario,
            Pago,
            Descuento,
            Subtotal,
            FechaInicio,
            Forma1,
            Importe1,
            Forma2,
            Importe2,
            idSucursal,
            Visible,
            FechaFin,
            Cancelado
        ) VALUES (
            $id_insert,
            $conceptoPago,
            NOW(),
            $costo,
            2,
            16,
            0.00,
            $costo,
            CURDATE(),
            'MercadoPago',
            0.00,
            'MercadoPago',
            0.00,
            $suc,
            $visible,
            $fecha_vencimiento,
            0
        )";

        if ($conn->query($query_pagos) === TRUE) {

            if($opcion == "97"){
                $querySocio = "UPDATE socios SET Activo = 1 WHERE idSocio = $id_cliente";
                $conn->query($querySocio);
            }

            $msgProceso = "PAGO PLAN INSERTADO";
        } else {
            $msgProceso = "ERROR INSERT PAGO PLAN: " . $conn->error;
        }

    } else {
        $msgProceso = "ERROR INSERT SOCIO_SERVICIO: " . $conn->error;
    }

} else {

    $costo = (float)$costo;
    $idLocker = (int)$idLocker;
    $lock_asig = (int)$lock_asig;
    $id_cliente = (int)$id_cliente;
    $concepto = (string)$concepto;
    $suc = (int)$suc;

    $queryLocker = "SELECT 
        lockers_socios.Socios_idSocio AS id,
        lockers.idLocker AS id_gl,
        locker.id_locker AS idlk_c,
        CONCAT(socios.Nombre, ' ', socios.Apellidos) AS name,
        lockers.Clave AS grupo,
        locker.num_locker AS num_locker,
        lockers_socios.FechaAsignacion AS pago,
        lockers_socios.FechaVencimiento,
        lockers_socios.concepto_pago AS concepto,
        lockers_socios.importe AS total,
        lockers_socios.estado AS status,
        lockers_socios.cancelado,
        sucursal.NombreSucursal AS sucursal
    FROM lockers_socios, socios, lockers, sucursal, locker
    WHERE lockers_socios.Lockers_idLocker = lockers.idLocker
    AND lockers_socios.Socios_idSocio = socios.idSocio
    AND lockers_socios.sucursal_idSucursal = sucursal.idSucursal
    AND socios.idSocio = $id_cliente
    AND lockers_socios.locker_asignado = locker.id_locker
    AND lockers_socios.cancelado = 0
    ORDER BY lockers_socios.id_lockers_socios DESC
    LIMIT 1";

    $resultadoL = $conn->query($queryLocker);
    $row_fecha = $resultadoL ? $resultadoL->fetch_assoc() : null;

    if ($row_fecha) {
        $fechaVen = $row_fecha['FechaVencimiento'];
    } else {
        $fechaVen = date('Y-m-d');
    }

    $addFecha = "DATE_ADD('$fechaVen', INTERVAL 1 DAY)";

    switch($concepto){
        case '1': $addFecha = "DATE_ADD('$fechaVen', INTERVAL 1 DAY)"; break;
        case '2': $addFecha = "DATE_ADD('$fechaVen', INTERVAL 7 DAY)"; break;
        case '3': $addFecha = "DATE_ADD('$fechaVen', INTERVAL 15 DAY)"; break;
        case '4': $addFecha = "DATE_ADD('$fechaVen', INTERVAL 1 MONTH)"; break;
        case '5': $addFecha = "DATE_ADD('$fechaVen', INTERVAL 6 MONTH)"; break;
        case '6': $addFecha = "DATE_ADD('$fechaVen', INTERVAL 12 MONTH)"; break;
    }

    $query = "INSERT lockers_socios(
        Lockers_idLocker,
        Socios_idSocio,
        locker_asignado,
        FechaAsignacion,
        FechaVencimiento,
        estado,
        concepto_pago,
        tipo_pago,
        cantidad_tarjeta,
        importe,
        user_idUsuario,
        sucursal_idSucursal,
        cancelado
    ) VALUES (
        '$idLocker',
        '$id_cliente',
        '$lock_asig',
        '$fechaVen',
        $addFecha,
        1,
        '$concepto',
        2,
        '$costo',
        '$costo',
        21,
        '$suc',
        0
    )";

    if($conn->query($query) == TRUE){
        $msgProceso = "PAGO LOCKER INSERTADO";
    }else{
        $msgProceso = "ERROR INSERT LOCKER: " . $conn->error;
    }
}

$msgProcesoSafe = $conn->real_escape_string($msgProceso);

$conn->query("
    UPDATE pagos_mercadopago_webhook
    SET procesado = 1,
        mensaje = '$msgProcesoSafe'
    WHERE payment_id = '$payment_id_safe'
    LIMIT 1
");

file_put_contents(
    __DIR__ . "/payment_detail_log.txt",
    "RESULTADO PROCESO payment_id=$payment_id: $msgProceso\n----------------------\n",
    FILE_APPEND
);

$conn->close();

echo "OK";