<?php
/**
 * /backreload/v1/dashboard — aggregated stats for the dashboard page.
 *
 * @package Backreload\Api
 */

namespace Backreload\Api;

use Backreload\Models\BackupRecord;
use Backreload\Models\DestinationRecord;

if ( ! defined( 'ABSPATH' ) ) { exit; }

class DashboardController extends BaseController {

	public function register( string $namespace ): void {
		register_rest_route( $namespace, '/dashboard', [
			'methods'             => 'GET',
			'callback'            => [ $this, 'show' ],
			'permission_callback' => [ $this, 'check_perm' ],
		] );
	}

	public function show() {
		$backups = BackupRecord::all( 100, 0 );
		$success = array_filter( $backups, fn( $b ) => 'success' === $b->status );
		$last    = $backups[0] ?? null;

		// 7-day series
		$series = [];
		$by_day = [];
		foreach ( $backups as $b ) {
			$day = substr( (string) $b->created_at, 0, 10 );
			$by_day[ $day ] = ( $by_day[ $day ] ?? 0 ) + $b->size;
		}
		for ( $i = 6; $i >= 0; $i-- ) {
			$d = gmdate( 'Y-m-d', strtotime( "-{$i} days" ) );
			$series[] = [
				'day' => gmdate( 'D', strtotime( $d ) ),
				'mb'  => round( ( $by_day[ $d ] ?? 0 ) / 1048576 ),
			];
		}

		// Storage by destination. Values are BYTES so the frontend can
		// format them with formatBytes() rather than hardcoding "GB". The
		// previous shape (GB as a float) made sub-gigabyte backups round
		// to "0 GB" which was useless for small sites.
		$by_dest = [];
		foreach ( DestinationRecord::all() as $d ) {
			try {
				$u = $this->plugin->get( 'destinations' )->handler( $d->type )->usage( $d );
			} catch ( \Throwable $e ) {
				$u = [ 'used' => 0, 'free' => 0, 'total' => 0 ];
			}
			$by_dest[] = [
				'name'  => $d->name,
				'type'  => $d->type,
				'used'  => (int) ( $u['used']  ?? 0 ),
				'free'  => (int) ( $u['free']  ?? 0 ),
				'total' => (int) ( $u['total'] ?? 0 ),
			];
		}

		$next_runs = $this->plugin->get( 'scheduler' )->combined_preview( 1 );
		$next      = $next_runs[0]['at'] ?? null;

		return $this->ok( [
			'last_backup'  => $last ? $last->to_array() : null,
			'total_count'  => count( $backups ),
			'storage_used' => array_sum( array_map( fn( $b ) => $b->size, $backups ) ),
			'success_rate' => count( $backups ) ? round( count( $success ) / count( $backups ) * 100 ) : 100,
			'next_run'     => $next,
			'series_7d'    => $series,
			'storage_by_destination' => $by_dest,
			'recent'       => array_map( fn( $b ) => $b->to_array(), array_slice( $backups, 0, 5 ) ),
		] );
	}
}
