<?php 

/*
    Author: Serezha
    Date: 11.05.18
*/

if ($photos = DB::$pdo->query('SELECT * FROM `photos` WHERE `id_user` = ? AND `id_album` = ? ORDER by `time`', [$data['id_user'], $data['id']])->fetchAll())
{
    foreach ($photos as $i)
    {
        foreach (['', '_64x', '_128x', '_150x', '_256x', '_512x', '_1080x'] as $size)
        {
            $path = FILES_PATH . System::$photosDir . $i['hash'] . $size . '.jpg';

            if (file_exists($path))
            {
                unlink($path);
            }
        }
        
        if ($user['avatar'] == $i['id'])
        {
            DB::$pdo->query("UPDATE `users` SET `info_avatar` = ?, `avatar` = ? WHERE `id` = ? LIMIT 1",  [NULL, 0, $data['id_user']]);
        }
        
        DB::$pdo->query('DELETE FROM `photos_comments` WHERE `id_photo` = ?', [$i['id']]);
    }
    
    DB::$pdo->query('DELETE FROM `photos` WHERE `id_album` = ?', [$data['id']]);
    DB::$pdo->query("UPDATE `users` SET `count_photos` = `count_photos` - ?, `count_albums` = `count_albums` - 1 WHERE `id` = ? LIMIT 1",  [count($photos), $data['id_user']]);
}
    
DB::$pdo->query('DELETE FROM `photos_album` WHERE `id` = ?', [$data['id']]);

System::redirect('Альбом успешно удален.', '/photos' . $data['id_user']);
