#!/usr/bin/perl

use strict;
use warnings;
use FindBin;
use lib "$FindBin::Bin/../../lib";    # t/lib
use Test::More;
use MT::Test::Env;
use utf8;
our $test_env;

BEGIN {
    $test_env = MT::Test::Env->new(
        DeleteFilesAtRebuild => 1,
        RebuildAtDelete      => 1,
    );
    $ENV{MT_CONFIG} = $test_env->config_file;
}

use MT::Test 'has_php';
BEGIN { plan skip_all => "Can't find executable file: php" unless has_php(); }

use MT::Test::PHP;
use MT::Test::ArchiveType;
use MT::Test::Fixture::ArchiveType;
use MT::Test::Tag;
use MT::Util::UniqueID;

use MT;
use MT::Template::Context;
my $app = MT->instance;

$test_env->prepare_fixture('archive_type');
my $objs = MT::Test::Fixture::ArchiveType->load_objs;
my $blog_id = $objs->{blog_id} or die;

$test_env->clear_mt_cache;

my @ct_maps = grep { $_->archive_type =~ /^ContentType/ }
    MT::Test::ArchiveType->template_maps;
for my $map ( sort { $a->archive_type cmp $b->archive_type } @ct_maps ) {

    $map->build_type(3);
    $map->save or die;

    $app->publisher->rebuild(
        ArchiveType => $map->archive_type,
        BlogID      => $blog_id,
        TemplateMap => $map,
    ) or die;

    my $fileinfo
        = $app->model('fileinfo')->load( { templatemap_id => $map->id } )
        or next;
    my $request_uri = $fileinfo->url;

    my $tmpl = $app->model('template')->load( $map->template_id ) or die;
    $tmpl->text(
        'content stash <MTIf tag="contentid">exists<MTElse>does not exist</MTIf>'
    );
    $tmpl->save or die;

    my $log = $ENV{MT_TEST_PHP_ERROR_LOG_FILE_PATH} ||
                File::Spec->catfile($ENV{MT_TEST_ROOT}, 'php-' . MT::Util::UniqueID::create_session_id() . '.log');

    my $test_script = <<PHP;
<?php
\$MT_HOME   = '@{[ $ENV{MT_HOME} ? $ENV{MT_HOME} : '.' ]}';
\$MT_CONFIG = '@{[ MT->instance->find_config ]}';
\$blog_id   = '$blog_id';

\$_SERVER['REQUEST_URI'] = '$request_uri';
\$log = '$log';
PHP

    $test_script .= <<'PHP';
include_once($MT_HOME . '/php/mt.php');
include_once($MT_HOME . '/php/lib/MTUtil.php');

$mt = MT::get_instance($blog_id, $MT_CONFIG);
$mt->config('PHPErrorLogFilePath', $log);
$mt->view();
PHP

    my $result = MT::Test::PHP->run($test_script);

    my $test_name;
    if ( $tmpl->content_type_id ) {
        my $ct_name = $tmpl->content_type->name;
        $test_name = $map->archive_type . " ($ct_name)";
    }
    else {
        $test_name = $map->archive_type;
    }

    my $expected
        = $map->archive_type eq 'ContentType'
        ? 'content stash exists'
        : 'content stash does not exist';
    is( $result, $expected, $test_name );

    my $php_error = MT::Test::PHP->retrieve_php_logs($log);

    if ($ENV{MT_TEST_IGNORE_PHP_WARNINGS} && $php_error) {
        SKIP: {
            local $TODO = 'for now';
            ok !$php_error, 'no php warnings';
        }
    } else {
        is($php_error, '', 'no php warnings');
    }
}

done_testing;

