<?php
/**
 * MTC - Trail camera battery estimation
 * Battery estimation and statistics.
 * @package My Trail Camera
 * @since 8.1.0
 */

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

// ============================================================================
// SHARED CONSTANTS AND HELPERS
// ============================================================================

define( 'MTCAM_BATTERY_CAPACITY', 4400 );   // mAh
define( 'MTCAM_STANDBY_DRAW',     0.1 );    // mA
define( 'MTCAM_DAY_VIDEO_DRAW',   300 );    // mA
define( 'MTCAM_NIGHT_VIDEO_DRAW', 750 );    // mA (IR illumination + processing)
define( 'MTCAM_BATTERY_VOLTAGE',  3.7 );    // V nominal Li-ion

/**
 * Video resolution power multiplier.
 *
 * Higher resolution = more processing power + faster SD write.
 *
 * @param string $resolution Resolution key (1080p, 2K, 4K).
 * @return float Factor 1.0–1.30.
 */
function mtcam_resolution_factor( $resolution ) {
    $map = array(
        '480p'  => 0.85,
        '720p'  => 0.90,
        '1080p' => 1.0,
        '1296p' => 1.08,
        '2K'    => 1.15,
        '4K'    => 1.30,
    );
    return $map[ $resolution ] ?? 1.0;
}

// ============================================================================
// STATISTICS
// ============================================================================

/**
 * Get days in field
 */
function mtcam_get_days_in_field($deploy_date, $stolen_date = null) {
    if (empty($deploy_date)) return 0;

    try {
        $start = new DateTime($deploy_date);
        $end = !empty($stolen_date) ? new DateTime($stolen_date) : new DateTime();

        $diff = $start->diff($end)->days;
        return $diff !== false ? $diff : 0;
    } catch (Exception $e) {
        return 0;
    }
}

/**
 * Calculate daily battery consumption for a camera.
 *
 * Shared between simple and full battery estimation.
 *
 * @param array $cam          Camera data.
 * @param array $profile_data Camera profile data.
 * @return array {
 *     @type float $daily_consumed Total daily consumption in mAh.
 *     @type float $standby_mah    Standby drain in mAh/day.
 *     @type float $day_video_mah  Day recording drain in mAh.
 *     @type float $night_video_mah Night recording drain in mAh.
 *     @type float $drain_4g       4G module drain in mAh/day.
 * }
 */
function mtcam_calculate_daily_consumption( $cam, $profile_data ) {
    $rec_mode     = $cam['rec_mode'] ?? 'video';
    $day_videos   = intval( $cam['rec_day_count'] ?? 1 );
    $night_videos = intval( $cam['rec_night_count'] ?? 2 );
    $rec_length   = intval( $cam['rec_length'] ?? 110 );
    $res_factor   = mtcam_resolution_factor( $cam['rec_resolution'] ?? '1080p' );

    $standby_mah    = floatval( $profile_data['drain_standby'] ?? ( MTCAM_STANDBY_DRAW * 24 ) );
    $drain_4g       = floatval( $profile_data['drain_4g'] ?? 0 );
    $drain_per_photo = floatval( $profile_data['drain_photo'] ?? 2.0 );

    if ( $rec_mode === 'photo' ) {
        $day_video_mah   = $day_videos  * $drain_per_photo;
        $night_video_mah = $night_videos * $drain_per_photo * 1.8;
    } else {
        $video_hours     = $rec_length / 3600;
        $day_video_mah   = $day_videos  * MTCAM_DAY_VIDEO_DRAW  * $video_hours * $res_factor;
        $night_video_mah = $night_videos * MTCAM_NIGHT_VIDEO_DRAW * $video_hours * $res_factor;
    }

    return array(
        'daily_consumed'  => $standby_mah + $day_video_mah + $night_video_mah + $drain_4g,
        'standby_mah'     => $standby_mah,
        'day_video_mah'   => $day_video_mah,
        'night_video_mah' => $night_video_mah,
        'drain_4g'        => $drain_4g,
    );
}

// ============================================================================
// BATTERY ESTIMATION
// ============================================================================

/**
 * Simple battery estimation (FREE tier).
 * Basic capacity / daily_drain calculation without weather API.
 *
 * @param array $cam Camera data.
 * @return array Battery estimate keyed array.
 */
function mtcam_estimate_battery_simple( $cam ) {
    $start_pct    = floatval( $cam['battery_pct'] ?? 100 );
    $deploy_date  = $cam['deploy_date'] ?? '';
    $has_solar    = mtcam_has_solar( $cam['power_type'] ?? 'lithium' );

    $profile     = function_exists( 'mtcam_get_camera_profile' ) ? mtcam_get_camera_profile( $cam['profile'] ?? 'custom' ) : array();
    if ( function_exists( 'mtcam_resolve_battery_spec' ) ) {
        $spec        = mtcam_resolve_battery_spec( $cam, $profile );
        $battery_cap = $spec['capacity_mah'];
        $chemistry   = $spec['chemistry'];
    } else {
        $spec        = array( 'preset_id' => '', 'chemistry' => 'primary_lifes2' );
        $battery_cap = intval( $profile['battery_capacity'] ?? MTCAM_BATTERY_CAPACITY );
        $chemistry   = 'primary_lifes2';
    }

    // Solar cameras with a last_checked date: calculate from last check, not deploy.
    $last_checked  = $cam['last_checked'] ?? '';
    $calc_start    = ( $has_solar && ! empty( $last_checked ) ) ? $last_checked : $deploy_date;

    $consumption     = mtcam_calculate_daily_consumption( $cam, $profile );
    $daily_consumed  = $consumption['daily_consumed'];

    // Pasívne samo-vybíjanie — pri Li-ion ~2 %/mesiac, pri LiFeS₂ zanedbateľné.
    $self_discharge_daily = function_exists( 'mtcam_self_discharge_daily_rate' )
        ? $battery_cap * mtcam_self_discharge_daily_rate( $chemistry )
        : 0;

    $days_in_field = mtcam_get_days_in_field( $deploy_date, $cam['stolen_date'] ?? '' );
    $calc_days     = mtcam_get_days_in_field( $calc_start, $cam['stolen_date'] ?? '' );
    $battery_mah   = ( $start_pct / 100 ) * $battery_cap;

    // Simple linear drain (no solar, no weather) + self-discharge.
    $total_drain = ( $daily_consumed + $self_discharge_daily ) * $calc_days;
    $battery_mah = max( 0, $battery_mah - $total_drain );

    // Today's partial consumption (even when calc_days = 0, i.e. last_checked is today).
    $hour_of_day          = (float) gmdate( 'G' ) + (float) gmdate( 'i' ) / 60.0;
    $today_consumed_partial = ( $daily_consumed + $self_discharge_daily ) * ( $hour_of_day / 24.0 );
    $battery_mah            = max( 0, $battery_mah - $today_consumed_partial );
    $total_drain           += $today_consumed_partial;

    $new_pct = $battery_cap > 0 ? ( $battery_mah / $battery_cap ) * 100 : 0;
    $new_pct = max( 0, min( 100, round( $new_pct, 1 ) ) );

    return array(
        'battery_pct'      => $new_pct,
        'consumed_mah'     => round( $daily_consumed, 1 ),
        'solar_gained_mah' => 0,
        'net_mah'          => round( -$daily_consumed, 1 ),
        'days_in_field'    => $days_in_field,
        'total_solar'      => 0,
        'total_consumed'   => round( $total_drain, 0 ),
        'weather'          => __( 'N/A (basic mode)', 'my-trail-camera' ),
        'cloud_pct'        => 0,
        'temperature'      => 0,
        'temp_factor'      => 1.0,
        'sun_hours'        => 0,
        'sun_hours_eff'    => 0,
        'sunrise'          => '',
        'sunset'           => '',
        'panel_blocked'    => false,
        'has_solar'        => $has_solar,
        'power_type'       => $cam['power_type'] ?? 'lithium',
        'snow_cover'       => false,
        'is_fog'           => false,
        'weather_source'   => 'none',
        'battery_preset'   => $spec['preset_id'],
        'battery_chemistry' => $chemistry,
        'battery_capacity' => $battery_cap,
        'self_discharge_mah' => round( $self_discharge_daily, 2 ),
        'log'              => '',
        'error'            => null,
    );
}

