<?php
ini_set('default_charset', 'UTF-8');
ob_start();

$IMAGE_DIRECTORY = 'c:/users/admin/dropbox/skiing/british/image';
$IMAGE_WEB_PATH = 'https://www.freestylesnowsports.co.uk/british/image';
$DATABASE_DIRECTORY = 'c:/users/admin/dropbox/socialcache/news';
$ADMIN_PASSWORD = 'Freestyle342112';

date_default_timezone_set("Europe/London");
header('Content-Type: text/html;charset=utf-8'); 

// DEV
//$IMAGE_DIRECTORY = 'Z:/htdocs/feed/images';
//$IMAGE_WEB_PATH = 'http://192.168.1.131/feed/images';
//$DATABASE_DIRECTORY = 'Z:/snowsports_posts';
//$ADMIN_PASSWORD = "pass";

///


$style = <<<EOF
<style>
.title {
    font-size: 21px;
    font-weight: 300;
    line-height: 24px;
    color: #292F33;
    margin: 5px;
    border-bottom: 1px solid rgba(15,70,100,.12);
}
.feed {
    font: normal normal 14px/1.4 Helvetica,Roboto,"Segoe UI",Calibri,sans-serif;
}
.twitter {
    border-top: 1px solid rgba(15,70,100,.12);
    border-bottom: 1px solid rgba(15,70,100,.12);
}
.admin .feed img {
    max-height:300px;
    max-width:300px;
    margin: 2px;
}
.feed img {
    max-height:100%;
    max-width:100%;
    margin: 2px;
}
.post {
    border-bottom: 1px solid rgba(15,70,100,.12);
    border-top: none;
    margin: 5px;
}
.body {
    white-space: pre-line;
}
.dates {
    margin-top: 15px;
    margin-bottom: 5px;
}
.edit-images img {
    max-height:200px;
    max-width:200px;
    margin: 2px;
}
</style>
EOF;


function sort_by_event_date($a, $b) {
    return $a->event_timestamp - $b->event_timestamp;
}

function datetime_to_timestamp($datetime) {
    return date_create_from_format("d/m/y H:i", $datetime, new DateTimeZone('Europe/London'));
}

function timestamp_to_datetime($timestamp) {
    $dt = new DateTime("@$timestamp");
    return $dt->format("d/m/y H:i");
}

function create_post_filepath($id) {
    global $DATABASE_DIRECTORY;
    return $DATABASE_DIRECTORY . "/post_" . $id . ".json";
}

function image_url($filename) {
    global $IMAGE_WEB_PATH;
    return $IMAGE_WEB_PATH . "/" . $filename;
}

function make_url_clickable($text) {
    $url_regex = '@(http)?(s)?(://)?(([a-zA-Z])([-\w]+\.)+([^\s\.]+[^\s]*)+[^,.\s])@';
    $text = preg_replace($url_regex, '<a href="http$2://$4" target="_blank" title="$0">$0</a>', $text);
    return $text;
}

function body_text_to_html($text) {
    $text = make_url_clickable($text);
    return $text; 
}

function write_post($id, $body, $event_datetime, $expiry_datetime, $images) {
    global $DATABASE_DIRECTORY;
    $event_timestamp = datetime_to_timestamp($event_datetime);
    $expiry_timestamp = datetime_to_timestamp($expiry_datetime);

    $data = array(
        "id" => $id,
        "body" => $body,
        "event_datetime" => $event_datetime,
        "expiry_datetime" => $expiry_datetime,
        "event_timestamp" => date_timestamp_get($event_timestamp),
        "expiry_timestamp" => date_timestamp_get($expiry_timestamp),
        "images" => $images
    );
    $json = json_encode($data, JSON_UNESCAPED_UNICODE);
    $filepath = $DATABASE_DIRECTORY . "/post_" . $id . ".json";
    file_put_contents($filepath, $json);
}

function create_post($body, $event_datetime, $expiry_datetime, $images) {
    $id = time() + rand(0, 1000);
    write_post($id, $body, $event_datetime, $expiry_datetime, $images);
}


function load_post_by_filename($filename) {
    global $DATABASE_DIRECTORY;
    $file = file_get_contents($filename);
    $json = json_decode($file);
    return $json;
}

function load_post($id) {
    $filepath = create_post_filepath($id);
    return load_post_by_filename($filepath);
}

function list_posts() {
    global $DATABASE_DIRECTORY;
    $posts = array();
    foreach (glob($DATABASE_DIRECTORY . "/post_*.json") as $filename) {
        $post = load_post_by_filename($filename);
        // If it's past the expiry time delete the file.
        if (time() > $post->expiry_timestamp) {
            unlink($filename);
            continue;
        }
        array_push($posts, $post);
    }
    usort($posts, "sort_by_event_date");
    return $posts;
} 

function delete_post($id) {
    global $DATABASE_DIRECTORY;
    if (is_numeric($id)) {
        $filename = create_post_filepath($id);
        @unlink($filename);
    }
    header("Location: " . strtok($_SERVER["REQUEST_URI"], '?') . "?action=admin", true, 301);
}


function admin_page_create_post_form() {
?>
    <h2>Create Post</h2>
    <form method="POST" enctype="multipart/form-data">
        <div class="create-post">
            <input type="hidden" name="action" value="create"/>
            Event Date/Time (dd/mm/yy hh:mm): <input type="text" name="event_datetime"/><br>
            Expiry Date/Time (dd/mm/yy hh:mm): <input type="text" name="expiry_datetime"/><br>
            Text: <textarea name="body" rows="5" cols="50"></textarea><br>
            Image 1: <input type="file" name="image_1"/><br><br>
            <!--Image 2: <input type="file" name="image_2"/>
            Image 3: <input type="file" name="image_3"/>
            -->
            <input type="submit" value="Submit"/>
        </div>
    </form>
<?php
}

function admin_page_create_edit_form($id) {
    $post = load_post($id);

    // Old posts are missing the datetime fields so we need to create them from the timestamps
    if (!isset($post->event_datetime)) {
        $post->event_datetime = timestamp_to_datetime($post->event_timestamp);
    }
    if (!isset($post->expiry_datetime)) {
        $post->expiry_datetime = timestamp_to_datetime($post->expiry_timestamp);
    }

?>
    <h2>Edit Post</h2>
    <form method="POST" enctype="multipart/form-data">
        <div class="create-post">
            <input type="hidden" name="action" value="edit"/>
            <input type="hidden" name="id" value="<?=$post->id?>"/>
            Event Date/Time (dd/mm/yy hh:mm): <input type="text" name="event_datetime" value="<?=$post->event_datetime?>"/><br>
            Expiry Date/Time (dd/mm/yy hh:mm): <input type="text" name="expiry_datetime" value="<?=$post->expiry_datetime?>"/><br>
            Text: <textarea name="body" rows="5" cols="50"><?=$post->body?></textarea><br><br>
            Images:<br>
            <div class="edit-images">
            <?php
            foreach ($post->images as $image) {
            ?>
                <div class="image">
                    <img src="<?=image_url($image)?>">
                    <input name="current_image_name" type="hidden" value="<?=$image?>"/>
                </div>
            <?php
            }
            ?>
            </div>
            Replace Image: <input type="file" name="image_1"/><br><br>
            <!--Image 2: <input type="file" name="image_2"/>
            Image 3: <input type="file" name="image_3"/>
            -->
            <input type="submit" value="Submit"/>
        </div>
    </form>
<?php
}

function admin_page_list_posts() {
    global $IMAGE_WEB_PATH;
    $posts = list_posts();
?>
    <div class="admin">
    <h1>Admin</h1>
    <a href="?action=new">Create Post</a>
    <hr><br><br>
    <div class="feed">
    <div class="title">News</div>
    <?php
    foreach ($posts as $post) {
?>
    <div class="posts">
    <div data-id="<?=$post->id?>" class="post">
        <div class="body">
            <?=body_text_to_html($post->body)?>
        </div>
        <div class="images">
            <?php
            foreach ($post->images as $image) {
            ?>
                <div class="image">
                    <img src="<?=$IMAGE_WEB_PATH . "/" . $image?>">
                </div>
            <?php
            }
            ?>
        </div>
        <div class="dates">
        <div class="timestamp">
            Starts: <?=date("d/m/y H:i", $post->event_timestamp)?>
        </div>
        <div class="expiry">
            Ends: <?=date("d/m/y H:i", $post->expiry_timestamp)?>
        </div>
        </div>
    <div class="post-actions">
        <a class="delete-button" href="?action=delete&id=<?=$post->id?>">Delete</a> | <a class="edit-button" href="?action=edit&id=<?=$post->id?>">Edit</a> 
    </div>
    </div>
    </div>
<?php
    }
?>
    </div>
    </div>
<?php
}

function page_list_posts() {
    global $IMAGE_WEB_PATH;
    $posts = list_posts();
?>
    <div class="feed">
    <div class="title">News</div>
    <?php
    foreach ($posts as $post) {
?>
    <div class="posts">
    <div data-id="<?=$post->id?>" class="post">
        <div class="body">
            <?=body_text_to_html($post->body)?>
        </div>
        <div class="images">
            <?php
            foreach ($post->images as $image) {
            ?>
                <div class="image">
                    <img src="<?=$IMAGE_WEB_PATH . "/" . $image?>">
                </div>
            <?php
            }
            ?>
        </div>
        <div class="dates">
        <div class="timestamp">
            Starts: <?=date("d/m/y H:i", $post->event_timestamp)?>
        </div>
        <div class="expiry">
            Ends: <?=date("d/m/y H:i", $post->expiry_timestamp)?><br>________________________________________
        </div>
        </div>
    </div>
    </div>
<?php
    }
?>
    </div>
<?php
}


function admin_login_page() {
?>
    <form method="POST">
        <div class="login">
            <input type="hidden" name="action" value="login"/>
            Password: <input type="text" name="password"/>
            <input type="submit" value="Submit"/>
        </div>
    </form>
<?php 
}

function check_admin_password($password) {
    global $ADMIN_PASSWORD;
    if ($password !== $ADMIN_PASSWORD) {
        return false;
    } else {
        return true;
    }
}

function verify_session() {
    if ($_SESSION["loggedin"] === true) {
        return true;
    } else {
        echo "Not logged in";
        return false;
    }
}

if (!file_exists($DATABASE_DIRECTORY)) {
    mkdir($DATABASE_DIRECTORY, 0777, true);
}
if (!file_exists($IMAGE_DIRECTORY)) {
    mkdir($IMAGE_DIRECTORY, 0777, true);
}


// POST
if (isset($_POST["action"])) {
    // Any actions require login
    session_start();
    verify_session();
    // Create post
    if ($_POST["action"] == "login") {
        if (check_admin_password($_POST["password"])) {
            session_regenerate_id();
            $_SESSION["loggedin"] = true;
            header("Location: " . strtok($_SERVER["REQUEST_URI"], '?') . "?action=admin", true, 301);
        } else {
            echo "Invalid Password";
        }
    } elseif ($_POST["action"] == "create") {
        $allowed_image_extensions = array("jpg", "png", "gif");
        $images = array();
        foreach (array("image_1", "image_2", "image_3") as $image) {
            if (!empty($_FILES[$image]['name']) && !empty($_FILES[$image]['tmp_name'])) {
                $filename = basename($_FILES[$image]["name"]);
                $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
                if (!in_array($extension, $allowed_image_extensions)) {
                    echo "Invalid image extension";
                    exit;
                }
                $new_filename = uniqid(rand(), true) . "." . $extension;
                move_uploaded_file($_FILES[$image]["tmp_name"], $IMAGE_DIRECTORY . "/" . $new_filename);
                array_push($images, $new_filename);
            }
        }
        create_post($_POST["body"], $_POST["event_datetime"], $_POST["expiry_datetime"], $images);
        header("Created: true");
        header("Location: " . strtok($_SERVER["REQUEST_URI"], '?') . "?action=admin", true, 301);
    } elseif ($_POST["action"] == "edit") {
        $allowed_image_extensions = array("jpg", "png", "gif");
        $images = array();

        if (isset($_FILES["image_1"]) && !empty($_FILES["image_1"]["name"]) && $_FILES["image_1"]["error"] != 0) {
            echo "Error uploading image.";
            exit;
        }
        if (!empty($_FILES["image_1"]['name']) && !empty($_FILES["image_1"]['tmp_name'])) {
            header("Replace-Image: true");
            // Replace image
            // TODO: Cleanup previous image(s)
            $filename = basename($_FILES["image_1"]["name"]);
            $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
            if (!in_array($extension, $allowed_image_extensions)) {
                echo "Invalid image extension";
                exit;
            }
            $new_filename = uniqid(rand(), true) . "." . $extension;
            move_uploaded_file($_FILES["image_1"]["tmp_name"], $IMAGE_DIRECTORY . "/" . $new_filename);
            array_push($images, $new_filename);
        } elseif (isset($_POST["current_image_name"]) && !empty($_POST["current_image_name"])) {
            // Keep original image
            array_push($images, $_POST["current_image_name"]);
        }
        write_post($_POST["id"], $_POST["body"], $_POST["event_datetime"], $_POST["expiry_datetime"], $images);
        header("Edited: true");
        header("Location: " . strtok($_SERVER["REQUEST_URI"], '?') . "?action=admin", true, 301);
    }
    exit;
} elseif (isset($_GET["action"])) {
    session_start();
    print $style;
    if ($_GET["action"] == "admin") {
        if (verify_session()) {
            admin_page_list_posts();
        } else {
            admin_login_page();
        }
    } elseif ($_GET["action"] == "new") {
        admin_page_create_post_form();
    } elseif ($_GET["action"] == "delete" && isset($_GET["id"])) {
        delete_post($_GET["id"]);
    } elseif ($_GET["action"] == "edit" && isset($_GET["id"])) {
        admin_page_create_edit_form($_GET["id"]);
    } else {
    }
} else {
    // Public feed
    print $style;
    page_list_posts();
}
