<?php

namespace App\Controllers;

use App\Core\Controller;
use App\Helpers\Auth;
use App\Helpers\Url;
use App\Models\PhotoAlbum;
use App\Models\Photo;
use App\Models\AuditLog;

class PhotoController extends Controller
{
    public function __construct()
    {
        parent::__construct();
    }

    public function albums()
    {
        $model = new PhotoAlbum();
        $albums = Auth::check() ? $model->getWithPhotos() : $model->getPublic();
        $this->view('photos/albums', ['albums' => $albums]);
    }

    public function album($params)
    {
        $albumId = $params['id'] ?? null;
        $albumModel = new PhotoAlbum();
        $album = $albumModel->find($albumId);

        if (!$album) {
            $_SESSION['error'] = 'Album not found';
            $this->redirect('/photos');
        }

        $photoModel = new Photo();
        $photos = $photoModel->getByAlbum($albumId);

        $this->view('photos/album', ['album' => $album, 'photos' => $photos]);
    }

    public function createAlbum()
    {
        Auth::requireLogin();
        $this->view('photos/create_album');
    }

    public function storeAlbum()
    {
        Auth::requireLogin();
        $model = new PhotoAlbum();
        $model->create([
            'title' => $_POST['title'] ?? '',
            'description' => $_POST['description'] ?? '',
            'is_public' => isset($_POST['is_public']) ? 1 : 0,
            'created_by' => Auth::id(),
        ]);

        $audit = new AuditLog();
        $audit->log(Auth::id(), 'photo.create_album', 'photo_albums', $model->db->lastInsertId(), "Created photo album: {$_POST['title']}");

        $_SESSION['success'] = 'Album created successfully';
        $this->redirect('/photos');
    }

    public function upload($params)
    {
        Auth::requireLogin();
        $albumId = $params['id'] ?? null;
        $albumModel = new PhotoAlbum();
        $album = $albumModel->find($albumId);

        if (!$album) {
            $_SESSION['error'] = 'Album not found';
            $this->redirect('/photos');
        }

        if (!isset($_FILES['photos'])) {
            $_SESSION['error'] = 'No photos uploaded';
            $this->redirect('/photos/album/' . $albumId);
        }

        $uploadDir = $_SERVER['DOCUMENT_ROOT'] . Url::getBaseUrl() . '/uploads/photos/';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }

        $photoModel = new Photo();
        $files = $_FILES['photos'];
        $fileCount = count($files['name']);
        $uploaded = 0;

        for ($i = 0; $i < $fileCount; $i++) {
            if ($files['error'][$i] !== UPLOAD_ERR_OK) continue;

            $ext = strtolower(pathinfo($files['name'][$i], PATHINFO_EXTENSION));
            $filename = 'photo_' . time() . '_' . $i . '.' . $ext;
            $dest = $uploadDir . $filename;

            if (move_uploaded_file($files['tmp_name'][$i], $dest)) {
                $size = getimagesize($dest);
                $photoModel->create([
                    'album_id' => $albumId,
                    'user_id' => Auth::id(),
                    'title' => $files['name'][$i],
                    'file_path' => '/uploads/photos/' . $filename,
                    'file_size' => $files['size'][$i],
                    'width' => $size ? $size[0] : null,
                    'height' => $size ? $size[1] : null,
                ]);
                $uploaded++;
            }
        }

        $audit = new AuditLog();
        $audit->log(Auth::id(), 'photo.upload', 'photos', $albumId, "Uploaded {$uploaded} photos to album: {$album->title}");

        $_SESSION['success'] = "{$uploaded} photos uploaded successfully";
        $this->redirect('/photos/album/' . $albumId);
    }

    public function deleteAlbum($params)
    {
        Auth::requireLogin();
        $id = $params['id'] ?? null;
        $model = new PhotoAlbum();
        $album = $model->find($id);

        if ($album) {
            $audit = new AuditLog();
            $audit->log(Auth::id(), 'photo.delete_album', 'photo_albums', $id, "Deleted photo album: {$album->title}");
            $model->delete($id);
            $_SESSION['success'] = 'Album deleted';
        }
        $this->redirect('/photos');
    }

    public function deletePhoto($params)
    {
        Auth::requireLogin();
        $id = $params['id'] ?? null;
        $photoModel = new Photo();
        $photo = $photoModel->find($id);

        if ($photo) {
            $filePath = $_SERVER['DOCUMENT_ROOT'] . Url::getBaseUrl() . '/' . ltrim($photo->file_path, '/');
            if (file_exists($filePath)) unlink($filePath);
            $photoModel->delete($id);
        }
        $this->redirect('/photos/album/' . ($photo->album_id ?? 0));
    }
}
