<?php

class MetaCampaignManager {
    
    const ACCESS_TOKEN = "EAAHGPOFDqwwBO7fZBnZBTI8rxma4SdgGzy8W83ShqBHti1TiZBbCTXqPtiPZC3MrQ0xElUqbf6Tx98dFAJlbumLpJfLdu4DYBgD9mTumrhjwUsgE1EypgAQr2iKpxdgOGX95JovRxc3Ku40TYd15Gx7JXEBXb9UgHpLuuGakKzwkghZCkIBj5XscFqW3BfIW4";
    const ACCOUNT_ID = '4398382103816289';

    public function __construct() {

    }

    public function getAdsetDetails() {
        $base_url = "https://graph.facebook.com/v24.0/act_" . self::ACCOUNT_ID . "/adsets";
        $params = http_build_query( [
            'fields' => 'id,name,campaign_id,campaign{name,daily_budget,lifetime_budget,budget_remaining,status},daily_budget,lifetime_budget,bid_amount,created_time',
            'limit' => 100,
            'access_token' => self::ACCESS_TOKEN
        ] );

        $page = 1;
        $result = [];
        $endpoint = $base_url . '?' . $params;

        do {
            $response = json_decode( file_get_contents( $endpoint ), true );

            if( !empty( $response['data'] ) ) {
                $result = array_merge( $result, $response['data'] );
            }

            $endpoint = $response['paging']['next'] ?? null;
            $page++;
        } while ( $endpoint );


        $data = [];
        if( !empty( $result ) ) {
            foreach( $result as $row ) {
                $budget = $row['daily_budget'] ?? $row['campaign']['daily_budget'];
                $budget = ROUND( $budget/100, 2 );
                $campaign = [
                    'name' => $row['name'],
                    'bid' => $row['bid_amount'],
                    'budget' => $budget,
                    'status' => $row['campaign']['status'],
                    'type' => $this->getCampaignType( $row['name'] ),
                    'created_on' => $row['created_time'],
                ];
                $data[$row['campaign_id']] = $campaign;
            }
        }

        return $data;
    }

    public function getCampaignType( $name ) {
        $type = 'OLD';
        $substring = substr( $name, 0, 8 );
        $valid = $this->isValidDate( $substring );
        if( $valid ) {
            $type = $this->checkDateStatus( $substring );
        }
        return $type;
    }

    function isValidDate($date, $format = 'Ymd') {
        $d = DateTime::createFromFormat($format, $date);
        return $d && $d->format($format) === $date;
    }

    function checkDateStatus( $date, $format = 'Ymd' ) {
        // Convert input string to DateTime
        $givenDate = DateTime::createFromFormat($format, $date);
        if( !$givenDate ) return "INVALID";

        // Today - 3 days
        $threeDaysAgo = new DateTime('-3 days');

        // Compare
        return ( $givenDate < $threeDaysAgo ) ? "OLD" : "NEW";
    }

}