<?php
/**
 * Created by PhpStorm.
 * User: jaskokoyn
 * Date: 2/19/2015
 * Time: 3:47 PM
 */

require('../../inc/db.php');
include('../../inc/functions.php');

$params                     =   getParams();
$output                     =   array('status' => 1);

if( !isReady( $params, array( "username" ) ) || !isset($_SESSION['loggedin']) ){
    dj($output);
}

$username                   =   secure($params['username']);
$mid                        =   intval($params['mid']);

// Get Chat Messages
$messagesQuery          =   $db->prepare("SELECT * FROM messages
                                          WHERE m_type = :mt AND id > :mid AND
                                          (
                                          ( submitted_by = :s1 AND recipient = :r1 ) OR
                                          ( submitted_by = :s2 AND recipient = :r2 )
                                          )
                                          ORDER BY `id` DESC LIMIT 25");
$messagesQuery->execute(array(
    ":mt"   =>  2,
    ":mid"  =>  $mid,
    ":s1"   =>  $_SESSION['username'],
    ":r1"   =>  $username,
    ":s2"   =>  $username,
    ":r2"   =>  $_SESSION['username']
));

if($messagesQuery->rowCount() > 0){
    $output['status']           =   2; // SUCCESS
}

// Set PMs to read
$updatePMQuery  =   $db->prepare("UPDATE messages SET isRead = :ir WHERE recipient = :r AND submitted_by = :sb");
$updatePMQuery->execute(array(
    ":ir"   =>  2,
    ":r"    =>  $_SESSION['username'],
    ":sb"   =>  $username
));

// Get PMs
$getPMQuery =   $db->prepare("SELECT *, COUNT(*) as `total` FROM messages
                              WHERE m_type = :t AND recipient = :r AND isRead = :ir GROUP BY `submitted_by`");
$getPMQuery->execute(array(
    ":t"    =>  2,
    ":r"    =>  $_SESSION['username'],
    ":ir"   =>  1
));
$getPMRow   =   $getPMQuery->fetchAll(PDO::FETCH_ASSOC);

$messagesRow                =   $messagesQuery->fetchAll(PDO::FETCH_ASSOC);
$output['messages']         =   array_reverse($messagesRow);
$output['mid']              =   end($output['messages']);
$output['pms']              =   $getPMRow;
dj($output);


// OLD


$response['status']     =   1;
$response['messages']   =   array_reverse($messagesRow);
$response['mid']        =   end($response['messages']);
$response['pmUsers']    =   $getPMRow;

die(json_encode($response));