Attribute VB_Name = "InternshipTools"
Option Explicit

' Macros for the creative internships workbook (db.sccrpg.com).
'
' To add them: Alt+F11, File > Import File, choose this file, close the editor,
' then save the workbook as "Excel Macro-Enabled Workbook (.xlsm)".
' Run them from View > Macros.
'
' Every macro works on the sheet named "Internships" and finds its columns by the
' header text in row 1, so the columns can be moved without breaking anything.
' None of them deletes a row or changes a description.

Private Const SHEET_NAME As String = "Internships"
Private Const LAST_ROW As Long = 500

Private Function Ws() As Worksheet
    Set Ws = ThisWorkbook.Worksheets(SHEET_NAME)
End Function

' Column number for a header, or 0 with a message if it is missing.
Private Function Col(ByVal header As String) As Long
    Dim c As Long, lastCol As Long
    lastCol = Ws.Cells(1, Ws.Columns.Count).End(xlToLeft).Column
    For c = 1 To lastCol
        If LCase$(Trim$(CStr(Ws.Cells(1, c).Value))) = LCase$(header) Then
            Col = c
            Exit Function
        End If
    Next c
    MsgBox "The column """ & header & """ was not found in row 1 of the " & SHEET_NAME & " sheet.", vbExclamation
    Col = 0
End Function

' Last row that holds an internship (by the Company column).
Private Function LastUsedRow() As Long
    Dim c As Long
    c = Col("Company")
    If c = 0 Then
        LastUsedRow = 1
    Else
        LastUsedRow = Ws.Cells(Ws.Rows.Count, c).End(xlUp).Row
    End If
End Function

' Jump to the first empty row and fill in today's date and the usual defaults.
Public Sub AddListing()
    Dim r As Long, cCo As Long, cChk As Long, cPost As Long, cPaid As Long, cMode As Long, cHow As Long
    cCo = Col("Company"): cChk = Col("Last checked"): cPost = Col("Posting")
    cPaid = Col("Paid"): cMode = Col("Remote or on site"): cHow = Col("Checked how")
    If cCo = 0 Or cChk = 0 Or cPost = 0 Or cPaid = 0 Or cMode = 0 Or cHow = 0 Then Exit Sub
    ShowAll
    r = LastUsedRow + 1
    If r > LAST_ROW Then
        MsgBox "The sheet is set up for " & (LAST_ROW - 1) & " internships and it is full. Ask the maintainer to extend it.", vbExclamation
        Exit Sub
    End If
    Ws.Cells(r, cChk).Value = Date
    Ws.Cells(r, cPost).Value = "Open posting"
    Ws.Cells(r, cPaid).Value = "Not stated"
    Ws.Cells(r, cMode).Value = "Not stated"
    Ws.Cells(r, cHow).Value = "Listing read"
    Ws.Activate
    Ws.Cells(r, cCo).Select
End Sub

' Set "Last checked" to today for every selected row. Use it after opening and reading the links.
Public Sub MarkCheckedToday()
    Dim cChk As Long, cCo As Long, area As Range, rw As Range, n As Long
    cChk = Col("Last checked"): cCo = Col("Company")
    If cChk = 0 Or cCo = 0 Then Exit Sub
    If Not ActiveSheet Is Ws Then
        MsgBox "Select rows on the " & SHEET_NAME & " sheet first.", vbInformation
        Exit Sub
    End If
    For Each area In Selection.Areas
        For Each rw In area.Rows
            If rw.Row > 1 And Not rw.EntireRow.Hidden Then
                If Len(Trim$(CStr(Ws.Cells(rw.Row, cCo).Value))) > 0 Then
                    Ws.Cells(rw.Row, cChk).Value = Date
                    n = n + 1
                End If
            End If
        Next rw
    Next area
    MsgBox n & " row(s) marked as checked today.", vbInformation
End Sub

' Open the internship link of each selected row in the browser (10 at most).
Public Sub OpenSelectedLinks()
    Dim cLink As Long, area As Range, rw As Range, n As Long, url As String
    cLink = Col("Internship link")
    If cLink = 0 Then Exit Sub
    If Not ActiveSheet Is Ws Then
        MsgBox "Select rows on the " & SHEET_NAME & " sheet first.", vbInformation
        Exit Sub
    End If
    For Each area In Selection.Areas
        For Each rw In area.Rows
            If rw.Row > 1 And Not rw.EntireRow.Hidden Then
                url = Trim$(CStr(Ws.Cells(rw.Row, cLink).Value))
                If LCase$(Left$(url, 7)) = "http://" Or LCase$(Left$(url, 8)) = "https://" Then
                    If n >= 10 Then
                        MsgBox "Opened the first 10. Select fewer rows at a time.", vbInformation
                        Exit Sub
                    End If
                    ThisWorkbook.FollowHyperlink url
                    n = n + 1
                End If
            End If
        Next rw
    Next area
    If n = 0 Then MsgBox "No web links in the selected rows.", vbInformation
End Sub

' Show only the rows for which keep(row) is true.
Private Sub HideExcept(ByRef keep() As Boolean)
    Dim r As Long
    Application.ScreenUpdating = False
    For r = 2 To UBound(keep)
        Ws.Rows(r).Hidden = Not keep(r)
    Next r
    Application.ScreenUpdating = True
End Sub

' Show every row again and clear any filter.
Public Sub ShowAll()
    On Error Resume Next
    If Ws.FilterMode Then Ws.ShowAllData
    On Error GoTo 0
    Ws.Rows("2:" & LAST_ROW).Hidden = False
End Sub

' Show only internships whose deadline falls in the next 30 days.
Public Sub ShowDeadlinesSoon()
    Dim cDead As Long, r As Long, last As Long, keep() As Boolean, n As Long, v As Variant
    cDead = Col("Deadline")
    If cDead = 0 Then Exit Sub
    ShowAll
    last = LastUsedRow
    If last < 2 Then Exit Sub
    ReDim keep(1 To last)
    For r = 2 To last
        v = Ws.Cells(r, cDead).Value
        If IsDate(v) Then
            If CDate(v) >= Date And CDate(v) <= Date + 30 Then
                keep(r) = True
                n = n + 1
            End If
        End If
    Next r
    HideExcept keep
    Ws.Activate
    MsgBox n & " internship(s) with a deadline in the next 30 days. Run ShowAll to see everything again.", vbInformation
End Sub

' Ask for a discipline and show the rows that list it as primary or other.
Public Sub FilterByDiscipline()
    Dim c1 As Long, c2 As Long, r As Long, last As Long, keep() As Boolean, n As Long, want As String
    c1 = Col("Primary discipline"): c2 = Col("Other disciplines")
    If c1 = 0 Or c2 = 0 Then Exit Sub
    want = Trim$(InputBox("Which discipline? For example: Motion, Packaging, UX/UI, Photography", "Filter by discipline"))
    If Len(want) = 0 Then Exit Sub
    ShowAll
    last = LastUsedRow
    If last < 2 Then Exit Sub
    ReDim keep(1 To last)
    For r = 2 To last
        If InStr(1, CStr(Ws.Cells(r, c1).Value) & ";" & CStr(Ws.Cells(r, c2).Value), want, vbTextCompare) > 0 Then
            keep(r) = True
            n = n + 1
        End If
    Next r
    HideExcept keep
    Ws.Activate
    MsgBox n & " internship(s) match """ & want & """. Run ShowAll to see everything again.", vbInformation
End Sub

' Show only the rows whose Check column is not OK.
Public Sub ShowProblems()
    Dim cChk As Long, cCo As Long, r As Long, last As Long, keep() As Boolean, n As Long, v As String
    cChk = Col("Check"): cCo = Col("Company")
    If cChk = 0 Or cCo = 0 Then Exit Sub
    ShowAll
    Application.Calculate
    last = LastUsedRow
    If last < 2 Then Exit Sub
    ReDim keep(1 To last)
    For r = 2 To last
        v = CStr(Ws.Cells(r, cChk).Value)
        If Len(v) > 0 And v <> "OK" Then
            keep(r) = True
            n = n + 1
        End If
    Next r
    If n = 0 Then
        MsgBox "Every row is OK.", vbInformation
        Exit Sub
    End If
    HideExcept keep
    Ws.Activate
    MsgBox n & " row(s) need attention. See the Check column. Run ShowAll to see everything again.", vbInformation
End Sub

' Remove stray spaces and add https:// to links typed without it. Changes nothing else.
Public Sub TidyUp()
    Dim heads As Variant, h As Variant, c As Long, r As Long, last As Long, s As String, t As String, n As Long
    last = LastUsedRow
    If last < 2 Then Exit Sub
    heads = Array("Company", "Location", "Role title", "Pay detail", "Other disciplines", "Term")
    Application.ScreenUpdating = False
    For Each h In heads
        c = Col(CStr(h))
        If c > 0 Then
            For r = 2 To last
                If Not Ws.Cells(r, c).HasFormula Then
                    s = CStr(Ws.Cells(r, c).Value)
                    t = Application.WorksheetFunction.Trim(s)
                    If t <> s Then
                        Ws.Cells(r, c).Value = t
                        n = n + 1
                    End If
                End If
            Next r
        End If
    Next h
    heads = Array("Company website", "Internship link")
    For Each h In heads
        c = Col(CStr(h))
        If c > 0 Then
            For r = 2 To last
                s = Trim$(CStr(Ws.Cells(r, c).Value))
                If Len(s) > 0 And InStr(1, s, "://") = 0 And InStr(1, s, ".") > 0 And InStr(1, s, " ") = 0 Then
                    Ws.Cells(r, c).Value = "https://" & s
                    n = n + 1
                End If
            Next r
        End If
    Next h
    Application.ScreenUpdating = True
    MsgBox n & " cell(s) tidied.", vbInformation
End Sub

' Save a copy of the Internships sheet as a CSV file beside this workbook.
' The website can also read the workbook itself, so this is only needed if a CSV is asked for.
Public Sub ExportForWebsite()
    Dim path As String, tmp As Workbook
    If Len(ThisWorkbook.path) = 0 Then
        MsgBox "Save the workbook first, so there is a folder to export into.", vbExclamation
        Exit Sub
    End If
    ShowAll
    path = ThisWorkbook.path & Application.PathSeparator & "internships-export-" & Format$(Date, "yyyy-mm-dd") & ".csv"
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    Ws.Copy
    Set tmp = ActiveWorkbook
    On Error GoTo Failed
    tmp.SaveAs Filename:=path, FileFormat:=62   ' 62 = CSV UTF-8 (Excel 2016 or later)
    tmp.Close SaveChanges:=False
    Application.DisplayAlerts = True
    Application.ScreenUpdating = True
    MsgBox "Saved " & path, vbInformation
    Exit Sub
Failed:
    On Error Resume Next
    tmp.Close SaveChanges:=False
    Application.DisplayAlerts = True
    Application.ScreenUpdating = True
    MsgBox "The export did not work (" & Err.Description & "). Send the workbook itself instead.", vbExclamation
End Sub
