<?php

class ProcessListLeadSharedLink  extends Core {

    function share() {

        $id = $_POST['id'];

        if (empty($id)) {
            http_response_code(400);
            echo json_encode(['error' => 'Parâmetros obrigatórios ausentes.']);
            exit;
        }
        $timezone = date_default_timezone_get();
        date_default_timezone_set('America/Sao_Paulo');
        $expires_at = (new DateTime())->modify('+1 hour')->format('Y-m-d H:i:s');

        $sql = "INSERT INTO process_list_lead_shared_links (process_list_lead_id, expires_at) VALUES (:id, :expires_at)";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([':id' => $id, ':expires_at' => $expires_at]);
        $last_insert_id = parent::$conn->lastInsertId();

        return ['id' => $last_insert_id];

    }

    function getShare() {

        $id = $_GET['id'];

        if (empty($id)) {
            http_response_code(400);
            echo json_encode(['error' => 'Parâmetros obrigatórios ausentes.']);
            exit;
        }

        $sql = "SELECT * FROM process_list_lead_shared_links WHERE id = :id";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([':id' => $id]);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$result) {            
            return ['type' => 'FAIL'];
        }

        $created_at = new DateTime($result['created_at'], new DateTimeZone('America/Sao_Paulo'));
        $now = new DateTime('now', new DateTimeZone('America/Sao_Paulo'));
        $diff_seconds = $now->getTimestamp() - $created_at->getTimestamp();
        $hours_left = ($diff_seconds > 0) ? $diff_seconds / 3600 : 0;
        
        if ($hours_left > 1) {
            return ['type' => 'EXPIRED'];
        }

        $sql = "UPDATE process_list_lead_shared_links SET access_count = access_count + 1  WHERE id = :id";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([':id' => $id]);

        return ['type' => 'OK'];
    }

}