<?php
if ( ! defined( 'ABSPATH' ) ) exit;

class Yatoon_SF_Database {

    public static function install() {
        global $wpdb;
        $charset_collate = $wpdb->get_charset_collate();
        $table = $wpdb->prefix . 'yatoon_sf_photos';

        $sql = "CREATE TABLE {$table} (
            id          BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
            platform    VARCHAR(20)     NOT NULL DEFAULT 'instagram',
            media_id    VARCHAR(120)    NOT NULL,
            media_url   TEXT            NOT NULL,
            thumbnail   TEXT,
            permalink   TEXT,
            caption     TEXT,
            media_type  VARCHAR(20)     DEFAULT 'IMAGE',
            taken_at    DATETIME,
            synced_at   DATETIME        NOT NULL,
            PRIMARY KEY  (id),
            UNIQUE KEY media_id (media_id),
            KEY platform (platform),
            KEY taken_at (taken_at)
        ) {$charset_collate};";

        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        dbDelta( $sql );

        $defaults = array(
            'fb_page_token'  => '',
            'fb_page_id'     => '',
            'fb_page_name'   => '',
            'ig_token'       => '',
            'ig_user_id'     => '',
            'ig_username'    => '',
            'ig_display_name'=> '',
            'columns'        => 4,
            'rows'           => 3,
            'gap'            => 8,
            'fb_columns'     => 4,
            'fb_rows'        => 3,
            'ig_columns'     => 4,
            'ig_rows'        => 3,
            'graph_version'   => 'v25.0',
            'display_mode'    => 'image',
            'layout'          => 'grid',
            'lightbox'        => 1,
            'show_caption'   => 0,
            'open_link'      => 1,
            'auto_sync'      => 'daily',
            'last_sync_ig'   => '',
            'last_sync_fb'   => '',
            'last_error_ig'  => '',
            'last_error_fb'  => '',
            'last_auto_sync_started'  => '',
            'last_auto_sync_finished' => '',
            'last_auto_sync_result'   => '',
            'custom_css'              => '',
            'ig_token_saved_at'       => '',
            'fb_sync_fail_count'      => 0,
            'ig_sync_fail_count'      => 0,
        );
        foreach ( $defaults as $key => $val ) {
            if ( get_option( 'yatoon_sf_' . $key ) === false ) {
                update_option( 'yatoon_sf_' . $key, $val );
            }
        }
    }
}
