<?php
defined('_VALID') or die('Restricted Access!');

if ( $config['photo_module'] == '0' ) {
    die();
}

require $config['BASE_DIR']. '/classes/filter.class.php';
require $config['BASE_DIR']. '/include/compat/json.php';
require $config['BASE_DIR']. '/include/adodb/adodb.inc.php';
require $config['BASE_DIR']. '/include/dbconn.php';
require $config['BASE_DIR']. '/include/sessions.php';

disableRegisterGlobals();

$response = array('status' => 0, 'msg' => '', 'debug' => '');
if ( isset($_POST['photo_id']) ) {
    if ( isset($_SESSION['uid']) ) {
        $filter     = new VFilter();
        $pid        = $filter->get('photo_id', 'INTEGER');                
        $uid        = intval($_SESSION['uid']);
        $sql        = "SELECT a.AID, a.UID FROM photos AS p, albums AS a
                       WHERE p.PID = " .$pid. " AND p.AID = a.AID
                       LIMIT 1";
        $response['debug'] = $sql;
        $rs         = $conn->execute($sql);
        if ( $conn->Affected_Rows() === 1 ) {
            $album  = $rs->getrows();
            $album  = $album['0'];
            if ( $album['UID'] == $uid ) {
                $tables = array('photos', 'photo_favorites', 'photo_comment', 'photo_flags', 'photo_rating_id', 'photo_rating_ip');
                foreach ($tables as $table) {
                    $sql    = "DELETE FROM " .$table. " WHERE PID = " .$pid. " LIMIT 1";
                    $conn->execute($sql);
                }
                $sql    = "UPDATE albums SET total_photos = total_photos-1 WHERE AID = " .$album['AID']. " LIMIT 1";
                $conn->execute($sql);
                $response['status'] = 1;
            } else {
                $response['msg'] = 'Failed to remove photo. Are you sure you are the owner of this photo?';
            }
        } else {
            $response['msg'] = 'Failed to remove photo. Are you sure you are the owner of this photo?';
        }
        
        $sql        = "DELETE FROM photo_favorites WHERE UID = " .$uid. " AND PID = " .$pid. " LIMIT 1";
        $conn->execute($sql);
    } else {
        $response['msg']   = 'Please login to remove photos from your albums!';
    }
}

echo json_encode($response);
die();
?>
