<?php
session_start();
require_once '../includes/config.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = intval($_POST['id']);
    $site_name = trim($_POST['site_name']);
    $location = trim($_POST['location']);
    $status = $_POST['status'];
    $contract_start = $_POST['contract_start'];
    $contract_end = $_POST['contract_end'];

    $start = new DateTime($contract_start);
    $end = new DateTime($contract_end);
    $interval = $start->diff($end);
    $totalMonths = ($interval->y * 12) + $interval->m;

    if ($totalMonths >= 12) {
        $years = floor($totalMonths / 12);
        $months = $totalMonths % 12;
        $duration = $years . ' year' . ($years > 1 ? 's' : '');
        if ($months > 0) {
            $duration .= ' ' . $months . ' month' . ($months > 1 ? 's' : '');
        }
    } else {
        $duration = $totalMonths . ' month' . ($totalMonths !== 1 ? 's' : '');
    }

    $stmt = $pdo->prepare("UPDATE sites SET site_name=?, location=?, status=?, contract_start=?, contract_end=?, contract_duration=? WHERE id=?");
    $stmt->execute([$site_name, $location, $status, $contract_start, $contract_end, $duration, $id]);

    header("Location: manage_sites.php");
    exit;
}
?>
