<?php
    session_start();

    require './connect.php';

    if(!isset($_SESSION['userid'])) {
        header("Location: ./Sign&Log.php");
    }
    
    $current_date = date('Y-m-d');

      // GET USER DETAILS
      $sql = "SELECT * FROM users WHERE userid = :userid";
      $stmt = $conn->prepare($sql);
      $stmt->bindParam(':userid', $_SESSION['userid'], PDO::PARAM_INT);
      $stmt->execute();
      $row = $stmt->fetch(PDO::FETCH_ASSOC);

      if(!isset($row['address'])) $row['address'] = "N/A";
      if(!isset($row['phone'])) $row['phone'] = "N/A";

      $row['membership_status'] = "N/A";
      $row['expired_date'] = "N/A";

      $sql = "SELECT * FROM member WHERE memberid = :userid";
      $stmt = $conn->prepare($sql);
      $stmt->bindParam(':userid', $_SESSION['userid'], PDO::PARAM_INT);
      $stmt->execute();

      $res = $stmt->fetch(PDO::FETCH_ASSOC);

      if($stmt->rowCount() > 0) {
        $row['membership_status'] = $res['membership_status'];
        $row['expired_date'] = $res['expired_date'];
      }

    // CHECK IF MEMBERSHIP IS EXPIRED
    if ($row['expired_date'] < $current_date && $row['membership_status'] == 'Active') {
        $update_sql = "UPDATE member SET membership_status = 'Inactive' WHERE memberid = :userid";
        $update_stmt = $conn->prepare($update_sql);
        $update_stmt->bindParam(':userid', $_SESSION['userid'], PDO::PARAM_INT);
        $update_stmt->execute();

        $row['membership_status'] = 'Inactive';
    }
    else if ($row['expired_date'] > $current_date && $row['membership_status'] == 'Inactive') {
      $update_sql = "UPDATE member SET membership_status = 'Inactive' WHERE memberid = :userid";
      $update_stmt = $conn->prepare($update_sql);
      $update_stmt->bindParam(':userid', $_SESSION['userid'], PDO::PARAM_INT);
      $update_stmt->execute();

      $row['membership_status'] = 'Active';
  }

  // LOAN QUERY
  $sql = "SELECT member.*, loan.* FROM users INNER JOIN member ON member.memberid = users.userid
          INNER JOIN loan ON loan.memberid = member.memberid
          WHERE users.userid = :userid;";
  $stmt = $conn->prepare($sql);
  $stmt->bindParam(':userid', $_SESSION['userid'], PDO::PARAM_INT);
  $stmt->execute();
  $loans = $stmt->fetchAll(PDO::FETCH_ASSOC);

  $loanCount = 0;

  $currentDate = new DateTime();

  $onTime = 0;
  $soon = 0;
  $overdue = 0;

foreach ($loans as $loan) {

  if ($loan['status'] == 'Returned') {
    continue;
  }

  $loanCount++;

  $loanDate = new DateTime($loan['loandate']);
  $dueDate = clone $loanDate;
  $dueDate->modify('+14 days'); 

  $daysSinceLoan = $currentDate->diff($loanDate)->days;


  if ($currentDate > $dueDate) {
    // Change status to Overdue
    $updateSql = "UPDATE loan SET status = 'Overdue' WHERE loanid = :loanid";
    $updateStmt = $conn->prepare($updateSql);
    $updateStmt->bindParam(':loanid', $loan['loanid'], PDO::PARAM_INT);
    $updateStmt->execute();
    $overdue++;
} elseif ($daysSinceLoan >= 11 && $daysSinceLoan <= 13) {
    // Change status to Soon
    $updateSql = "UPDATE loan SET status = 'Soon' WHERE loanid = :loanid";
    $updateStmt = $conn->prepare($updateSql);
    $updateStmt->bindParam(':loanid', $loan['loanid'], PDO::PARAM_INT);
    $updateStmt->execute();
    $soon++;
} elseif ($daysSinceLoan < 11) {
    // Change status to On Time
    $updateSql = "UPDATE loan SET status = 'On Time' WHERE loanid = :loanid";
    $updateStmt = $conn->prepare($updateSql);
    $updateStmt->bindParam(':loanid', $loan['loanid'], PDO::PARAM_INT);
    $updateStmt->execute();
    $onTime++;
}

}

// BOOK QUERY
  $sql = "SELECT loan.*, book.* 
          FROM loan 
          INNER JOIN Book_Copies ON loan.bookcopyid = Book_Copies.copyid
          INNER JOIN Book ON Book_Copies.bookid = book.bookid
          WHERE loan.memberid = :memberid;";

  $stmt = $conn->prepare($sql);
  $stmt->bindParam(':memberid', $_SESSION['userid'], PDO::PARAM_INT);
  $stmt->execute();
  $results = $stmt->fetchAll(PDO::FETCH_ASSOC);



// FINE QUERY

$sql = "SELECT 
    fine.*, 
    loan.*, 
    member.*, 
    Book_Copies.*, 
    book.*, 
    fine.status AS fine_status, 
    loan.status AS loan_status
    FROM fine
    INNER JOIN loan ON fine.loanid = loan.loanid
    INNER JOIN member ON loan.memberid = member.memberid
    INNER JOIN Book_Copies ON loan.BookCopyID = Book_Copies.copyid
    INNER JOIN book ON Book_Copies.bookid = book.bookid
    WHERE member.memberid = :memberid;";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':memberid', $_SESSION['userid'], PDO::PARAM_INT);
$stmt->execute();
$fines = $stmt->fetchAll(PDO::FETCH_ASSOC);

$totalFine = 0;
foreach ($fines as $fine) {
    if ($fine['fine_status'] == 'Unpaid') {
        $totalFine += $fine['fineamount'];
    }
}

?>

<!DOCTYPE html>
    <html>
    <head>
        <title>Profile</title>
        <link rel="stylesheet" href="CSS/Profile.css">
    </head>
    <body>
    <?php include 'Components/Header.html';?>

    <div class="container">
        <div class="page-header">
          <h1 class="page-title">My Account</h1>
          <p class="welcome-text">Welcome back, <?php echo $row['firstname']." ".$row['lastname'] ?></p>
        </div>

        <div class="account-grid">
            <div class="account-card">
              <div class="card-header">
                <svg class="card-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path>
                  <circle cx="12" cy="7" r="4"></circle>
                </svg>
                <h2 class="card-title">Account Details</h2>
              </div>
              <div class="card-content">
                <p><?php echo $row['firstname']." ".$row['lastname'] ?><br><?php echo $row['email'] ?><br>********</p>
                <a href="./EditProfile.php" class="action-link">Edit Profile</a>
              </div>
            </div>
      
            <div class="account-card">
              <div class="card-header">
                <svg class="card-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <rect x="1" y="4" width="22" height="16" rx="2" ry="2"></rect>
                  <line x1="1" y1="10" x2="23" y2="10"></line>
                </svg>
                <h2 class="card-title">Payment Methods</h2>
              </div>
              <div class="card-content">
                <p>Visa ending in 2027<br>Expires 12/27</p>
                <a href="#" class="action-link">Manage Payment Methods</a>
              </div>
            </div>
      
            <div class="account-card">
              <div class="card-header">
                <svg class="card-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"></path>
                  <circle cx="12" cy="10" r="3"></circle>
                </svg>
                <h2 class="card-title">Addresses</h2>
              </div>
              <div class="card-content">
                <p><?php echo $row['address'] ?></p>
                <p><?php echo $row['phone'] ?></p>
                <a href="./EditProfile.php" class="action-link">Manage Addresses</a>
              </div>
            </div>
      
            <div class="account-card">
              <div class="card-header">
                <svg class="card-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path>
                  <circle cx="12" cy="7" r="4"></circle>
                </svg>
                <h2 class="card-title">Membership</h2>
              </div>
              <div class="card-content">
              <p>Status: <?php echo $row['membership_status']; ?><br>Valid until: <?php echo $row['expired_date']; ?></p>
              <a href="<?php echo $row['membership_status'] != 'Suspended' ? './Renew.php' : '#'; ?>" class="action-link <?php echo $row['membership_status'] == 'Suspended' ? 'disabled' : ''; ?>" 
                <?php echo $row['membership_status'] == 'Suspended' ? 'onclick="return false;"' : ''; ?>>
                  Renew
              </a>
              </div>
            </div>

            <div class="account-card">
              <div class="card-header">
                <svg class="card-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path>
                  <circle cx="12" cy="7" r="4"></circle>
                </svg>
                <h2 class="card-title">Actions</h2>
              </div>
              <div class="card-content">
                <a href="./Logout.php" class="action-link">Logout</a>
              </div>
            </div>

          </div>
    
        <div class="account-summary">
          <div class="summary-card">
            <div class="card-header">
              <svg class="card-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"></path>
                <path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"></path>
              </svg>
              <h2 class="card-title">Account Overview</h2>
            </div>
            <div class="stat-grid">
              <div class="stat-item">
                <div class="stat-value"><?php echo $loanCount ?></div>
                <div class="stat-label">Items Borrowed</div>
              </div>
              <div class="stat-item">
                <div class="stat-value"><?php echo $onTime + $soon ?></div>
                <div class="stat-label">Items On Hold</div>
              </div>
              <div class="stat-item">
                <div class="stat-value"><?php echo $overdue ?></div>
                <div class="stat-label">Overdue Items</div>
              </div>
              <div class="stat-item">
                <div class="stat-value">$<?php echo number_format($totalFine, 2)?></div>
                <div class="stat-label">Current Fines</div>
              </div>
            </div>
          </div>
    
          <div class="summary-card alert">
            <div class="card-header">
              <svg class="card-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <circle cx="12" cy="12" r="10"></circle>
                <line x1="12" y1="8" x2="12" y2="12"></line>
                <line x1="12" y1="16" x2="12.01" y2="16"></line>
              </svg>
              <h2 class="card-title">Alerts</h2>
            </div>
            <div class="card-content">
              <p>You have <?php echo $overdue ?> overdue item/s and $<?php echo number_format($totalFine, 2)?> in unpaid fines.</p>
              <p style="margin-top: 8px"><?php echo $soon ?> item/s is due in the next 3 days.</p>
              <a href="#" class="action-link">View Details</a>
            </div>
          </div>
        </div>

        <?php 
        function generateLoanCards($loans, $results) {
        // Start the section card container
        echo '<div class="section-card">';
        echo '<h2 class="section-title">Current Loans</h2>';
        echo '<table class="loan-table">';
        
        // Generate table header
        echo '<thead>
                <tr>
                    <th>Title</th>
                    <th>Borrowed Date</th>
                    <th>Due Date</th>
                    <th>Status</th>
                    <th>Actions</th>
                </tr>
            </thead>';
        
        echo '<tbody>';
        
        // Loop through loans and match with book details
        foreach ($loans as $loan) {
            // Skip returned books
            if ($loan['status'] == 'Returned') {
                continue;
            }
            
            // Find matching book details
            $bookTitle = '';
            foreach ($results as $book) {
                if ($book['loanid'] == $loan['loanid']) {
                    $bookTitle = $book['title'];
                    break;
                }
            }
            
            // Calculate due date
            $loanDate = new DateTime($loan['loandate']);
            $dueDate = clone $loanDate;
            $dueDate->modify('+14 days');
            
            // Get status class
            $statusClass = '';
            switch ($loan['status']) {
                case 'Overdue':
                    $statusClass = 'status-overdue';
                    break;
                case 'Soon':
                    $statusClass = 'status-due-soon';
                    break;
                case 'On Time':
                    $statusClass = 'status-ontime';
                    break;
            }
            
            $formatted_date = DateTime::createFromFormat('Y-m-d', $loan['loandate'])->format('M d, Y');
            // Generate the row
            echo "<tr>";
            echo "<td>" . htmlspecialchars($bookTitle) . "</td>";
            echo "<td>" . $formatted_date . "</td>";
            echo "<td>" . $dueDate->format('M d, Y') . "</td>";
            echo "<td><span class='status-badge {$statusClass}'>" . $loan['status'] . "</span></td>";
            echo "<td>";
            
            // Handle renewals based on status
            if ($loan['status'] == 'Overdue') {
                echo "<button class='renewal-btn' onclick='returnWithFine(" . $loan['loanid'] . ")'>Return & Pay Fine</button>";
            } else {
                //echo "<button class='renewal-btn'>Return Book</button>";
                echo "<button class='renewal-btn' onclick='returnBook(" . $loan['loanid'] . ")'>Return Book</button>";
            }
            
            echo "</td>";
            echo "</tr>";
        }
        
        echo '</tbody>';
        echo '</table>';
        echo '</div>';
      }

        ?>
    
      <?php generateLoanCards($loans, $results); ?>


      <?php
        function generateFineCards($fines) {
        // Start the section card container
        echo '<div class="section-card">';
        echo '<h2 class="section-title">Fines & Fees</h2>';
        echo '<table class="loan-table">';

        // Generate table header
        echo '<thead>
                <tr>
                    <th>Date</th>
                    <th>Description</th>
                    <th>Amount</th>
                    <th>Status</th>
                </tr>
            </thead>';

        echo '<tbody>';

        
        $totalUnpaid = 0;
        $hasUnpaidFines = false;
        // Loop through fines
        foreach ($fines as $fine) {
            $fineDate = new DateTime($fine['finedate']);
            $formattedFineDate = $fineDate->format('M d, Y');

            $fineAmount = number_format($fine['fineamount'], 2);

            if ($fine['fine_status'] === 'Unpaid') {
              $totalUnpaid += $fine['fineamount'];
              $hasUnpaidFines = true;
          }
            // Generate the row
            echo "<tr>";
            echo "<td>" . $formattedFineDate . "</td>";
            echo "<td>Late Return - " . htmlspecialchars($fine['title']) . "</td>";
            echo "<td class='fine-amount'>$" . $fineAmount . "</td>";
            echo "<td>" . htmlspecialchars($fine['fine_status']) . "</td>";
            echo "</tr>";
        }

        echo '</tbody>';
        echo '</table>';

        if ($hasUnpaidFines) {
          $formattedTotal = number_format($totalUnpaid, 2);
          echo '<a href="#" class="action-link-pay" data-total="' . $totalUnpaid . '" onclick="payFines(); return false;">
                  Pay Fines Online (Total: $' . $formattedTotal . ')
                </a>';
      }

        echo '</div>';
    }
?>

    <?php generateFineCards($fines); ?>
        
    
      <script src="Scripts/Profile.js"></script>

      <?php include 'Components/Footer.html';?>
    </body>
</html>